I have been working on a small application using Next.js and Nest.js. One of the functionalities I implemented is a /login call in my client, which expects an HttpOnly Cookie from the server in response. Upon receiving a successful response, the user should be redirected to the homepage, where authentication is required. Although I can see the cookie in the network request's response headers, I'm unsure if I've missed something as the cookie is not present in the request headers in my middleware without manually setting it. Another potential issue I noticed is that after logging in, I can view the cookie using document.cookie in the browser console.
Server:
@Public()
@HttpCode(HttpStatus.OK)
@Post('signIn')
async signIn(@Body() signInDto: SignInDto, @Res() response: Response) {
const { access_token, role } = await this.authService.signIn(
signInDto.username,
signInDto.password,
);
response.cookie('jwt', access_token, {
sameSite: 'lax',
path: '/',
secure: false,
httpOnly: true,
});
response.send({ message: 'Authentication Successful', role });
}
Client:
const LoginPage = () => {
// should we move this out to an api folder?
async function handleSubmit(e: FormData) {
"use server";
// const formData = new FormData(e.get);
const username = e.get("username");
const password = e.get("password");
const response = await fetch("http://localhost:8080/auth/signIn", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ username, password }),
});
console.log("response in cookie ", response.headers.get("Set-Cookie"));
// without this I cannot see the cookie in the browser nor can I make the call on my homepage
const setCookieHeader = response.headers.get("Set-Cookie");
if (setCookieHeader) {
const jwtToken = setCookieHeader.split(";")[0].split("=")[1];
console.log("JWT Token:", jwtToken);
cookies().set({ name: "jwt", value: jwtToken, secure: true, path: "/" });
}
// if (!response.ok) doesn't work investigate
if (!response.ok) {
console.log("Invalid username or password");
// how can we display an error here without state?
return;
}
// redirect to homepage on success
redirect("/");
}