Having difficulty requesting an API in Next.js that relies on a backend cookie

1: When a user logs in, I generate a refresh token and create a cookie using 'cookie-parser'. This cookie is then sent to the path '/user/refresh-token'

res.cookie('refreshtoken', refreshtoken, {
        httpOnly: true,
        path: '/user/refresh-token',
        maxAge: 1000 * 60 * 60 * 24 * 7,
      });

2: However, when I try to fetch the cookie from the path 'user/refresh-token', I am always getting error 400 indicating that the cookie cannot be read. Strangely, when testing the API on Postman, I can see the cookie without any issues. It seems like there's a problem fetching this specific API route on the client side after logging in.

refreshToken: async (req, res) => {
    try {
      const refreshtoken = req.cookies.refreshtoken;
      if (!refreshtoken) {
        return res
          .status(400)
          .json({ msg: "not authenticated, signup or login" });
      }

3: The client-side code utilizes createContext as shown below:

export const DataProvider = ({children}) => {
    const [token, setToken] = useState(false)

     useEffect(()=> {
        const firstLogin = localStorage.getItem('firstLogin')
        if(firstLogin){
            const refreshToken = async ()=>{
                const res = await fetch('http://localhost:8000/user/refresh-token')
                await res.json();
            }
            refreshToken()
         }
     }, [])

5: To summarize, when a user logs in, a cookie is generated and stored at '/user/refresh-token' path. An item named 'firstLogin' is created and saved in local storage to indicate that the user is logged in. The page then redirects to '/' using 'window.location.href', followed by the context function attempting to fetch the API where the cookie exists. However, this results in an error 400 due to no cookies being sent.

Answer №1

fetch will only send cookies for cross-origin requests if you specify the credentials option as true.

const options = { credentials: true };
const res = await fetch('http://localhost:8000/user/refresh-token', options)

Please be aware that using this configuration will trigger a preflight request, so you may need to adjust the CORS settings on your server.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it better to have JavaScript and HTML in separate files or combined into a single HTML file?

Do you notice any difference when coding in both HTML and JavaScript within a single .html file compared to separating HTML code in a .html file and JavaScript code in a .js file? Does the functionality remain the same in both scenarios? For example, in t ...

What is the process for integrating Express middleware after implementing Apollo-Server v2 middleware?

I've encountered a unique issue while working with Express and Apollo Server. Despite searching online for solutions, it seems like this requirement is specific to me. My dilemma arises when I attempt to integrate an Express middleware after using th ...

Verify if the data in the Express request is an array

Recently, I've been working on an Express 3.x API server and facing the challenge of implementing support for batch requests at a specific endpoint. Despite not having the control to upgrade to 4.x, I am determined to find a solution. Currently, the e ...

Issues encountered while trying to integrate chessboard.js into a Vue application

I am facing an issue while trying to incorporate chessboard.js into my jetstream-vue application. Following the creation of the project, I executed the command npm install @chrisoakman/chessboardjs which successfully downloaded the package into my node_mod ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

The title tag's ng-bind should be placed outside of the element

When using ng-bind for the title tag inside the header, it seems to produce unexpected behavior. Here is an example of the code: <title page-title ng-bind="page_title"></title> and this is the resulting output: My Page Sucks <titl ...

Using JavaScript to save a file with a data URL in Internet Explorer

Need help with file conversion on different browsers. I developed an app that converts files, and everything was working perfectly in Chrome. However, when it comes to IE (10/11/Edge), I'm facing some challenges: 1) The HTML5 download attribute does ...

What is the method for executing a function enclosed within a variable?

As someone new to the world of Java, I have encountered a puzzling issue with some code related to a game. Specifically, there seems to be an obstacle when it comes to utilizing the navigator function. When I click on this function in the game, some sort o ...

Tips on showcasing the elements within a div container using flexbox

Seeking advice on positioning items/cards using flexbox in my initial react app. The issue lies with the div within my card component where applying display: flex; turns every card into a block (column-like) structure, flexing only the content within each ...

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

Steps to display the Sidebar on top of the main information page

One unique feature of my website is the FiltersSideBar located on the left side of the page. It contains various filters to refine search results. To optimize user experience, I implemented a function that hides the sidebar at specific browser window size ...

How can I adjust the height of an iframe dynamically using AngularJS?

I wrote a function that resizes the height of an iframe element to always be 100% after it loads: app.directive('iframeAutoSize', [function() { return { restrict: 'A', link: function(scope, element, attrs) { ...

Encountered an issue with trying to access the 'map' property of an undefined value while using Express and VueJS

Currently, I am in the process of developing a fullstack application utilizing Express, VueJS, and Mongoose. The app functions as a news feed platform. A couple of days ago, I encountered an error which was resolved with the help of your guidance. However, ...

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

Exploring sagas: Faking a response using a call effect

In my current scenario, I am facing a challenging situation: export function* getPosts() { try { const response = yield call(apiCall); yield put({ type: "API_CALL_SUCCESS", response }); } catch(e) { // ... } Furthermore, there is a spec ...

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

Convert the property that starts with XX from XML to JSON

I am currently working on a function that looks like this request.execute('[someSP].[spSomeSP]', function(err, dataset) { _.map(dataset, function(items) { console.log(items); }); }); When the _.map(...) is executed, it retu ...

Endless asynchronous loops with setInterval()

My nodejs application requires multiple infinite loops that call asynchronous functions. I was contemplating the following approach: async function process1() { ...perform some asynchronous tasks... } async function process2() { ...perform some as ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

How to use RegExp to locate the final return statement within a JavaScript code string

Take a look at this code snippet: cont x = 10; function foo() { return x; // ;; end of function ;; // /* here is a some text here too */ } function bar() { return 10 } return foo() + bar(); // ;;done;; // /* yolo yolo */ This string cont ...