next.jscookiesjwtnestjssetcookie

In Next, how can I access the JWT token from the cookie I am setting in my NestJS app?


I am stuck on this problem for a while now: I am trying to set a http only cookie in my Nest backend to store a jwt token that I can later access in my Next client.

The part that should set it is this:

@Post("auth/sign-in")
  async signIn(@Body() credentials: SignInDto, @Res() res: Response) {
    try {
      const { user, token }: { user: Partial<User>; token: string } =
        await this.userService.signIn(credentials);

      delete user.password;

      res.cookie("jwt", token, { httpOnly: true, sameSite: "none" });

      res.status(200).send({ user: user });
    } catch (err: unknown) {
      throw new InternalServerErrorException(err);
    }
  }

I then try to send a request to my backend this way:

const API_BASE_URL = 'http://localhost:8080';

export const signIn = async (email: string, password: string) => {
    try {
        const response = await axios.post(`${API_BASE_URL}/user/auth/sign-in`, {
            email,
            password,
        }, {withCredentials: false});

        if (response.status === 200) {
            console.log('User signed in successfully:', response.data);
            
            console.log(response.headers['set-cookie']); // returns undefined
            
            return response;
        } else {
            return null;
        }
    } catch (error) {
        console.error('Error signing in:', error);
        return null;
    }
}

When I inspect the request in the browser's networking tab, I can see the Set-Cookie with the correct jwt token, but apart from that I can't reach it.

I tried reading it from the response set-cookie header, but it will always be undefined no mather the CORS configuration I set. I also noticed when I inspect the site cookies, I can't see it either.

Can someone help me explain what I'm doing wrong or how can I access the cookie in my Next frontend?

Edit: I also set these when starting my nest app:

app.enableCors({
    origin: "http://localhost:3000",
    credentials: true,
  });

Solution

  • withCredentials should be true to include cookies.

    const response = await axios.post(
       `${API_BASE_URL}/user/auth/sign-in`,
       { email, password },
       { withCredentials: true }
    );