Get the cookies from the NodeJs API using Next.js version 13.4

Could you please review my code? I have a Next.js and Node API app, and I'm facing an issue with obtaining the cookie from my API in my Next app. The signInUser API that I created should return a generated JWT cookie. However, when I use it in my Next app, it doesn't appear in the devtools application-cookies. Oddly, when testing the API using Postman or Thunder Client, I can see the JWT token in the cookies tab. What could be causing this discrepancy?

Below is my backend Node API code for the signin process:

const app = express();
app.use(cors());

export const signInUser = async (
  req: express.Request,
  res: express.Response
) => {
  // Code for signing in a user goes here
}

This is the custom generateToken method used to generate a JWT token and set it as a cookie in the response object:

generateToken(res, user.id);
res.status(200).json(response);

Now, let's take a look at the frontend Next.js code for the signin functionality:

const handleSignIn = async (values: z.infer<typeof formSchema>) => {
   // Handling sign-in logic in the frontend
}

If anyone has any insights on why the JWT cookie isn't being received correctly in the Next.js app, your help would be greatly appreciated. Thank you!

Answer №1

One possibility to consider is that res.cookie may not be setting cookies for different domains. Postman operates without enforcing the same-origin policy or imposing the same security restrictions as web browsers. The functionality of cors is typically enforced by the browser, which could explain why it seems to work in Postman. If you configure CORS in Express using the following options:

import cors from "cors";

const options: cors.CorsOptions = {
  allowedHeaders: [
    "Origin",
    "X-Requested-With",
    "Content-Type",
    "Accept",
    "X-Access-Token",
  ],
  credentials: true,
  methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
  origin: "http://localhost:3000", // specify port for next.js
  preflightContinue: true,
};
const app = express();

app.use(cors(options));

Answer №2

To ensure proper authentication, make sure to include 'withCredentials: true' in your code snippet:

const response = await axios.post(SIGNIN_URL, values ,{ withCredentials: true });

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

Every time Tailwind compiles, it seems to generate a glitchy class

There was a time when I accidentally wrote 2 classes without a space max-w-[412px]mb-[36px]. This caused an error, so I added a space between the classes. However, the error persisted even after making this correction. In a last attempt to resolve the issu ...

The created date value is missing in the returned object for the voice call

I am currently developing an express/nodejs application that triggers a DB event and then makes multiple calls to notify about a special occurrence. These calls are made using Twilio for NodeJS. However, after making the call, the returned object contains ...

Encountering a Network Error and experiencing a blank dropdown with React-Select Async component

I recently integrated react-select into my React application. The API endpoint I'm working with responds with data structured like this: [ { value: 123, label: "Michael Carrick", first_name: "Michael", last_name: "Carrick", coun ...

Dynamic row height in Material-UI DataGrid adjusting based on text content

When working with the DataGrid, I'm struggling to find a way to adjust row heights based on the length of text in each cell dynamically. I thought about utilizing renderCell on the column containing longer text and incorporating the <Typography> ...

Encountering a deployment issue on Vercel while building with NextJS

I'm facing issues while attempting to deploy my Nextjs app on Vercel: Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: (0 , react_development_.useState) is not a function or its ret ...

Redirecting with NextAuth on a t3 technology stack

Recently, I set up a new T3 app using the NextJs app router. With NextAuth configured and some providers added, everything appears to be in order. However, once I log in, I keep getting redirected to a link that leads to a non-existent page: http://localho ...

Determining if the state in React has been altered

State containing client information is stored here const { info, setInfo, onPostInfoChanges } = useContext(ClientInfos); Below is a function that sends new info data to the server using POST or PUT requests const onSubmitHandler = async (model) => { ...

Choose JSON information and modify it utilizing NODE.js with identical data

Feeling stuck.. I have a JSON file with some data and I need to manipulate it. Take a look at my JSON structure: [{ "method": "GET", "path": "/", "aliases": "", "name": "rootPath", "handler": "generatedApps/avion01/actions.HomeHandler" }, { "method": "GET ...

I aim to implement a delay in my route until all the processes are completed using Node.js

I have a slightly complex route where I need to customize the data retrieved from the database using Mongoose. The array of objects returned contains another array of IDs from a different collection, which I need to add as a new property to each object. He ...

Is there a way for me to incorporate a feature that verifies whether an email address is already registered before allowing the person to sign up?

I am currently working with Node.js, express.js, mongoose, and pug to develop a registration/login system. I have successfully stored the name and email in a mongoose database with specified schema for these fields. The data is sent from a pug page via a p ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...

Using Node.js to write data to a JSON file

Currently, I am working on a program that scans through an array containing numerous links. It reads through each link, extracts specific text, and then stores it in an output file as JSON. However, I am facing an issue with formatting the JSON file. The ...

Exploring Next.js: The difference between Client Side Navigation and direct html modifications

Currently, I am diving into the next.js tutorial, but there are some aspects that have me puzzled: In the tutorial, it mentions here, that when you click a <Link> element, it does not trigger a server request but instead performs "Client-side naviga ...

Is there a way to deactivate keyboard input on an HTML number input field? How about in a React or Material-UI environment?

I am working with an <input> tag that has the attribute type="number", and I want to disable keyboard input so that users are required to adjust the value using the spinner (up and down arrows). This will allow me to consume the input value on each c ...

Utilize Material UI links in React JS to connect to another component seamlessly

I'm completely new to React and have been struggling for hours to navigate to another component that I've created. My goal is to link my login form to the sign-up page once a Material UI link is clicked, but I just can't seem to get it to fu ...

Unwinding asynchronous Dilemma

I am completely new to Recoil and I have a query regarding asynchronous operations in Recoil. Consider the code snippet below: const usersState = atom({ key: "userInfo", default: { email: "", name: "" } }) ...

It appears that my React component is not being rerendered even after using componentDidMount and setState to update it

/*I have successfully fetched data and set it to state, however, when attempting to generate an array of jsx items for display, the array appears empty and nothing is rendering. I tried hardcoding and it worked. I also logged the data which showed that th ...

Result is not defined after aggregating in MongoDB with Mongoose framework

I am struggling to retrieve comments from a MongoDB collection (using Mongoose) and compute the total number of comments as well as the average rating using the aggregate pipeline. However, if the initial $match query returns no results, the script crashes ...

The $pull functionality of Waterline ODM used to query and update a MongoDB database

The Waterline feature of Sails allows you to designate an entity's attribute as an 'array' type: module.exports = { attributes: { items: { type: 'array' } } } In MongoDB, the $pull operator is available for update queri ...

There are no JavaScript files in the app bundle during the AU run

After recently updating my Aurelia application to the latest version, I am encountering a runtime error without any build-time errors being reported. The error message reads: Uncaught TypeError: Cannot read property '__useDefault' of undefined a ...