Next.js Discord

Discord Forum

Cannot access cookie in route.ts, but works perfectly in layout.tsx

Answered
rex1410 posted this in #help-forum
Open in Discord
Avatar
I have 2 NextJS web apps. The first sets adata in http only cookies and then opens the next web app. I want the 2nd web app to use these cookies for user verification.

In the 2nd app, I can access and log the cookies on localhost when trying to access them from layout.tsx but it does not work when I do the same in one of my route.ts file.

But they should be accessible by the server right?
Answered by rex1410
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

because when you consume your own endpoint from a server component and use cookies(), it's looking for cookies of the server component request
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
View full answer

3 Replies

Avatar
Found the answer
Avatar
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

because when you consume your own endpoint from a server component and use cookies(), it's looking for cookies of the server component request
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
Answer