1

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,
  });
2
  • try origin: ['localhost:3000'], Commented May 20, 2024 at 2:57
  • 1
    withCredentials: true should be there. Commented May 20, 2024 at 3:55

1 Answer 1

3
+50

withCredentials should be true to include cookies.

const response = await axios.post(
   `${API_BASE_URL}/user/auth/sign-in`,
   { email, password },
   { withCredentials: true }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.