NextJS httpsOnly cookie JWT Auth

Viewed 29

I'm trying to use JWT authentication for my app and save the token as an httpOnly cookie to use for subsequent requests. The requests work in Insomnia, setting and then using the cookie to login, but don't work in my NextJS frontend.

My frontend is at localhost:3000 and my backend is at localhost:3001 but I have cors set.

app.use(
  cors({
    origin: "http://localhost:3000",
    optionsSuccessStatus: 200,
    credentials: true,
  })
);

app.use(cookieParser());

My request for data once logged in looks like this:

const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      credentials: "include",
      body: JSON.stringify(data),
    };

fetch(url, options)
    .then((res) => res.json())
    .then((res) => {
        // Do stuff
    });

On the server I set the token using

res.cookie("token", token, {
        httpOnly: true,
        secure: true,
      });

but when I console log req.cookies.token on the server for the data request I get undefined. Is there something I'm doing wrong that's preventing the cookie from getting set/sent?

Or is this related to localhost not setting cookies? I thought that didn't apply for httpOnly cookies. Thanks!

1 Answers

You're setting the secure parameter on your cookie. This means that the browser will drop the cookie if the connection to your backend is not over SSL.

You would have to configure your backend to use SSL (probably with some self-signed certificates) or set the secure parameter on your cookie to false.

Related