#cookies
1 messages · Page 1 of 1 (latest)
Setting cookies in Next.js should be done in a Server Action (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or Route Handler (https://nextjs.org/docs/app/building-your-application/routing/route-handlers) as HTTP does not allow setting cookies after streaming starts. This is mentioned in the Next.js documentation (https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options).
Your code seems correct, but it's important to ensure that it's being called in the right context. If it's not being called within a Server Action or Route Handler, it might not work as expected.
Also, make sure that the expiresAt date is in the future. If it's in the past, the cookie will expire immediately and won't be set.
If you're still facing issues, it might be due to a bug or a specific configuration in your application. There are open issues in the Next.js GitHub repository where users have reported problems with setting cookies, such as this one (https://github.com/vercel/next.js/issues/70068). You might find some useful information or workarounds in the discussion there.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@river snow Kapa.ai is still learning and improving, please let me know how I did by reacting below.
@chrome trail hm, setting the cookie in the callback handler seems to work, but it doesn't work if i instead call a function which is located in another file
Let me check the knowledge base for you again. Give me one moment! :books:
The issue you're experiencing might be related to the context in which the function is being called. In Next.js, cookies can only be set in a Server Action or Route Handler. If the function is being called outside of these contexts, it won't be able to set the cookie.
Here's a simplified example:
// This won't work
export function setSessionTokenCookie(token: string, expiresAt: Date) {
cookies().set("session", token, {
httpOnly: true,
sameSite: "lax",
secure: prodMode,
expires: expiresAt,
path: "/"
});
}
// In your route handler or server action
setSessionTokenCookie("token", new Date());
Instead, you should do something like this:
// In your route handler or server action
cookies().set("session", "token", {
httpOnly: true,
sameSite: "lax",
secure: prodMode,
expires: new Date(),
path: "/"
});
If you need to use the function in multiple places, consider passing the cookies function as a parameter:
export function setSessionTokenCookie(cookiesFunc: any, token: string, expiresAt: Date) {
cookiesFunc().set("session", token, {
httpOnly: true,
sameSite: "lax",
secure: prodMode,
expires: expiresAt,
path: "/"
});
}
// In your route handler or server action
setSessionTokenCookie(cookies, "token", new Date());
This way, you're ensuring that the cookies().set function is being called in the correct context.