-
Notifications
You must be signed in to change notification settings - Fork 27.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Docs: Setting cookies in API Route Handlers isn't working at all. Unlike in middleware #52799
Comments
for me, setting cookies is working as expected, but when calling getting cookies from a route handler, there are no cookies (null)
|
I'm having the same issue. Under /app/page.tsx, I have
Under /app/api/config/route.ts
I tried both commented and uncommented in route.ts, but none of this is working |
Would you please provide the code you used to set the cookie? |
I'm right there with you... I tried both and even setting a Set-Cookie header, none worked. Btw, I think that if you update Typescript to the latest version you won't need these @ts-ignore anymore. |
I noticed that the fetch response has set-cookie inside the headers
|
Yes, the set-cookie header is shown when I log the headers and yet, no cookie... |
I made some further tests. I created another api route under pages folder import { NextApiRequest, NextApiResponse } from 'next';
import { serialize } from 'cookie';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const cookie = serialize('hello-cookie', 'api-hello-cookie-value', {
path: '/',
});
res.setHeader('Access-Control-Expose-Headers', '*');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Credentials', 'true');
// res.setHeader('Set-Cookie', `token1=token1`);
res.setHeader('Set-Cookie', cookie);
res.status(200).json({ name: 'John Doe' });
} I noticed that pointing the browser to http://localhost:4200/api/testapi, the cookie is correctly set and it is available to whole application. export async function getConfig() {
const configRes = await fetch('http://localhost:4200/api/prova');
console.log(configRes);
return await configRes.json();
}
export default async function Index() {
await getConfig();
return <div>Index Page </div>;
} it doesn't work |
I made an almost complete codesandbox here https://codesandbox.io/p/sandbox/silly-cookies-vhlvvn check it out. |
Hi everyone, this is the expected behavior, but we should explain it better in the docs. You cannot set cookies during render (inside Pages, Layouts, etc.). When a fetch request is made (eg. via a Route Handler), the You can verify this by directly visiting an endpoint that uses Route Handlers. (Observation here #52799 (comment)) When using Server Actions, the recommendation is to import the logic of the Route Handler instead of doing a fetch call, since you can set cookies via |
Hi, thanks for the answer. Yet, it is still confusing to me. The link you've provided to set a cookie in a Route Handler is using server action, which I'm not because it is still experimental. Other than that, how am I supposed to access/trigger that cookie function in the Route Handler if I can't fetch the Route? You talk about "directly visiting an endpoint". Am I supposed to redirect my users to a blank /api page just for the cookie to be set? This looks like a wobbly, barely effective workaround. But I guess it doesn't even matter. Because my use case is involving a fetch request. During that fetch, depending on the data obtained, I want to set a corresponding cookie. Given what you said, Nextjs is intentionally built to make it impossible... |
"You can set cookies using Route Handlers" Isn't it a bit conflicting or am I getting something wrong? |
Hello @kapsule-studio. Not sure if this is already been suggested regarding the primary issue, but I think the issue is that when rendering your page, the Some solutions you may try:
Both of these approaches are in this CodeSandbox example. You may have to run them locally to notice cookies being set. I did not see them getting set in the CodeSandbox environment. |
I've read the docs and tried many times but still fail, cookies still undefined.. How to get cookies with Update:
|
I keep getting this error Is possible set cookie on server side? 'use server'
import { cookies } from 'next/headers'
async function deleteCookie(name: string) {
cookies().delete(name)
} This function is called in the server component. |
Ohh, I got it, sending a request from client to server only sent the cookies, but making a api call during the render phase inside of server component won't send the cookies, since the client is the one who has the cookies, but in this case we are dealing with server to server |
Is there anyway to make sure that cookies is sent even in the api call made inside server components?? |
I have same issue in 14.0.1, the doc said we can set the cookie in server action - https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations#setting-cookies |
You should be able to set cookies in both Server Actions and Route Handlers. The documentation is correct. If you are seeing an issue, please open a new issue with a reproduction so we can investigate your case. Thanks! |
This closed issue has been automatically locked because it had no new activity for 2 weeks. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you. |
What is the improvement or update you wish to see?
The current doc on how to set a cookie in the route handler using the app router is wrong. No matter what I try, I never get to set the cookie. Yet, the same method works in the middleware function.
Is there any context that might help us understand?
Help please
Does the docs page already exist? Please link to it.
https://nextjs.org/docs/app/building-your-application/routing/router-handlers#cookies
DX-1790
The text was updated successfully, but these errors were encountered: