Read existing cookies in Route Handlers
Answered
devjiwonchoi posted this in #help-forum
Using
Example:
cookies() or NextRequest.cookies, is it not possible to return the existing cookie?Example:
// Server Component
cookies().set('token', 'token')// route.ts
// ...
return NextResponse.json({ token: cookies().get('token') })Answered by European sprat
because when you consume your own endpoint from a server component and use cookies(), it's looking for cookies of the server component request
9 Replies
European sprat
this is one of the reasons why consuming your own route handlers in a server component is anti-pattern
if it's absolutely necessary to consume your own route handler in a server component, you could try setting a header that is sent to the route handler with the same cookie value and in the route handler you check for either cookie or header
So basically it is not possible for route.ts to get cookies directly based on the name?
This docs is confusing me:
https://nextjs.org/docs/app/building-your-application/routing/route-handlers#cookies
This docs is confusing me:
https://nextjs.org/docs/app/building-your-application/routing/route-handlers#cookies
European sprat
it is possible but not if you're setting them in a server component and then hitting the route handler in the same request
I see, if you don't mind, could you check out this repro created by gabrielgrs?
https://github.com/gabrielgrs/next-cookies-test
Basically the cookie is set on authentication, then the Server Component fetches from the api route. Although the cookie is already set to the browser and is accessible by
TL;DR
After the cookie is set, we're trying to fetch on api route but returns undefined.
https://github.com/gabrielgrs/next-cookies-test
Basically the cookie is set on authentication, then the Server Component fetches from the api route. Although the cookie is already set to the browser and is accessible by
cookies() in Server Component, the route.ts gives undefined.TL;DR
After the cookie is set, we're trying to fetch on api route but returns undefined.
European sprat
because when you consume your own endpoint from a server component and use cookies(), it's looking for cookies of the server component request
Answer
European sprat
as far as the route handler is concerned, the browser request doesn't exist when the request comes from the server component
so you either need to pass it as say a header or just not do this at all and call the functions you need directly
Got it. Really appreciate it, thanks