I seem to be encountering challenges when trying to set cookies from a NestJS backend into my Next.js app.
My NestJS application is running on port 3001 and here is my bootstrap setup:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: 'http://localhost:3000',
credentials: true,
});
app.use(cookieParser());
await app.listen(3001);
}
bootstrap();
To test it, I have created a GET endpoint:
@Get()
async getAll(@Req() request: Request, @Res() response: Response) {
console.log(request.cookies);
response.cookie('name', 'value', {
httpOnly: true,
secure: false,
sameSite: 'none',
});
return response.send('ok');
}
In the Next.js file src/app/api/signin/route.ts, I have the following code:
'use server'
import { NextRequest, NextResponse } from "next/server";
import axios, { AxiosHeaderValue } from 'axios';
import { cookies } from "next/headers";
export async function POST(request: NextRequest, res: NextResponse) {
const response = await axios.get("http://localhost:3001/test", {
headers: {
"Content-Type": "application/json"
},
withCredentials: true,
});
console.log(response.headers)
return new NextResponse(JSON.stringify(response.data))
}
All seems well, as the console logs print the set-cookie:
Object [AxiosHeaders] {
'x-powered-by': 'Express',
'access-control-allow-origin': 'http://localhost:3000',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'set-cookie': [ 'name=value; Path=/; HttpOnly; SameSite=None' ],
'content-type': 'text/html; charset=utf-8',
'content-length': '2',
etag: 'W/"2-eoX0dku9ba8cNUXvu/DyeabcC+s"',
date: 'Tue, 19 Mar 2024 09:45:14 GMT',
connection: 'keep-alive',
'keep-alive': 'timeout=5'
}
However, if I call the same endpoint again, the console.log(request.cookies);
in the backend returns null.
Shouldn't the set-cookie directive set the cookie in the backend? And with axios withCredentials, shouldn't it use them?
What am I missing? The Next.js tutorials are somewhat confusing, and despite trying for the past two days, I can't seem to successfully set the cookies on the request...