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

Tips for effectively reusing the modal component in Vue.js without encountering re-render issues

I'm encountering an issue where the same component content is being rendered despite having different components (Rendering problem). I have a reusable modal component called modal.vue, so every time I create a new component, I call the modal compone ...

Inspecting Mapped Data in React using the Console

For some reason, I am unable to console.log any selection when using onClick in this React component. My goal is to achieve the following functionality. https://codesandbox.io/s/great-ardinghelli-6seko?file=/src/demoComponent.jsx I have successfully fetc ...

`Nodejs: Difficulty in transferring a variable from app.js to Index.html`

I've been struggling for the past two days to perform this operation but without success. Here is what I have tried in App.js: var express = require('express'), app = express(), httpServer = http.Server(app); app.use(express.static(__d ...

What is the best way to retrieve the value from a callback function in the outer scope?

I'm facing an issue with accessing values from a callback function in the parent scope. Essentially, I need to retrieve and use data fetched by the s3.getObject() function in the outer scope (last line). Below is my JavaScript code used for fetching ...

Prop in a React component is undergoing mutation

I encountered a strange situation where a prop in a React component is being changed. Although it's technically not a mutation since it's an array in JavaScript, it should not be modified. To replicate the issue, I created a simple example: htt ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Executing an AJAX POST request from one domain (localhost:9393) to another domain (localhost:9696) using Spring Rest

I am encountering an issue with a form on one app running on localhost:9393. The JavaScript function used to post data is: function registerClient() { var postData = $("#client-reg").serializeArray(); var formURL = "http://localhost:9393/mPaws/client/re ...

Refreshing browser data with JQuery ajax when the browser is refreshed

Is there a way in JavaScript or jQuery to stop the page from refreshing (F5) and only update certain parts of the page using Ajax? I attempted the following code, but it did not work: $(window).bind('beforeunload', function(event) { ...

Should reports be created in Angular or Node? Is it better to generate HTML on the client side or server side

I have a daunting task ahead of me - creating 18 intricate reports filled with vast amounts of data for both print and PDF formats. These reports, however, do not require any user interaction. Currently, my process involves the following: The index.html ...

Access the uploaded file as a stream through Express

I'm currently working on an API that includes a function to upload files to another website, acting as a proxy for the file upload process through the API. The destination website requires specific steps to be followed (such as sending the destinatio ...

Querying a map within a Mongo function results in an empty variable when accessed outside of the function, but

Currently, I am facing an issue while trying to create an array of objects using the map function in Mongo and node/express JS. Strangely, when I utilize console.log outside the map function, the array appears empty. However, within the map function, each ...

Display a few HTML elements sourced from a different online platform

I am trying to extract a specific value from a span element on another website and render it on my own website using either a GET/FETCH request or some other method. Currently, I have this code but I am struggling to extract the data I need. The data I am ...

Error: the keyword "module" has not been properly defined

Struggling to run this web app, initially encountered: (node:12960) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. C:\Users\J\react-messenger\stream-chat-boilerp ...

My PHP errors and success messages are not being displayed properly after an AJAX success

After making an AJAX call to submit a form, I would like to display either the PHP success message or error message upon completion. This is my current AJAX success function: success: function (data) { resultSuccess = $(data).find("#success") ...

Sharing package JSON file dependencies with child engines and addons in Ember.js

I am seeking information on how Ember Js can share the parent app's package.json file dependency (xyz:3.0.0) with child engines and addons without them needing to redeclare the dependencies in their own package.json files. This is to reduce the overal ...

Execute with jQuery using Multiple Attribute Selector

I am attempting to input numeric values using a keyboard. My issue is as follows: the keyboard has an "Accept" button, and I have multiple text fields. I want to assign a different action for each text field. I attempted to use multiple attribute selector ...

Selenium webdriver was not able to find the specified div element

Currently, I am working on automating a scenario where a user searches for an item and once the search results are displayed, they click on the serving size and quantity of that specific item. https://i.sstatic.net/GV02V.jpg However, I keep encountering ...

The ng-controller directive is not functioning accurately

I attempted to execute the following basic HTML: <!DOCTYPE html> <html ng-app="tempApp"> <head> <script src="js_libs/angular/angular.min.js"></script> <script src="js_libs/angular/bootstrap.js"></script&g ...

What is the best way to keep track of dynamically inserted input fields?

I've created a form with two text boxes: one for entering people's "name" and another for their "surname." By clicking on the page, you can add additional pairs of text boxes for both "name" and "surname," allowing users to input as many pairs as ...

The Architecture of a Node.js Application

I'm curious about the efficiency of my nodejs app structure in terms of performance optimization. My main concern lies in how I handle passing around references to my app object across modules. Basically, in my app.js file, I define all my dependenci ...