Home > Software engineering >  Why browser can't set cookies by default
Why browser can't set cookies by default

Time:08-30

I know there are a lot of discussion about this topic already did. and i think i have followed all the instruction but still can't succeed.I think i'm missing something.

Here's my cookie :

 const cookieOptions = {
    expires: new Date(
      Date.now()   process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
    path: '/',
    sameSite: 'lax',
    maxAge: 1000 * 60 * 60 * 1,
  };
  if (process.env.NODE_ENV === 'production') {
    cookieOptions.secure = true;
  }

  res.cookie('jwt', token, cookieOptions);

Cors :

app.use(
  cors({
    origin: ['http://localhost:3000'],
    credentials: true,
  })
);

Frontend :

const { data } = await axios.post(
        "http://127.0.0.1:8000/api/v1/users/login",
        {
          email: enteredEmail,
          password: enteredPassword,
        },
        { withCredentials: true }
      );

I have also used axios.defaults.withCredentials = true; . But still i can't find my jwt in Application > cookies.

Here's my Response header enter image description here

and this is my request header

enter image description here

CodePudding user response:

"res.cookie()" only set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265.If you take a look closely at the response header, see that jwt=... is present in the Set-Cookie header.

For your implementation, where you try to access the data from the axios response, you should look into res.json() or res.send(), as it directly sends the response back in the body, not the header.

  • Related