Next.js Discord

Discord Forum

Not getting cookies in App router

Unanswered
anjan_kp posted this in #help-forum
Open in Discord
I am regretting it after migrating to the app router.
Not able to get cookies..
Cookies are basics of any web application. Why did the nextjs team break it in the app router?
They could have kept the good things off the page router.
Why should I write a middle ware to read cookies?
Can you suggest any other alternative to cookies which I can read from server?

15 Replies

what troubles do you have with cookies()?
@Barbary Lion
you don't need to write down middleware to read cookie
I am able to set the cookies but am not able to read them on the page.tsx. I am trying to set a cookie if search-param is preview which is working but on the route change the cookie is being reset because the query-param resets..
so you basically want to read cookies in the client component, right?
No.. I want to read in app router page.tsx file
@anjan_kp what's the trouble?
I am able to set the cookie but on next route it's getting reset. I came to know that it's happening because of streaming and the workaround is the middleware
The cookie should stay till it expires. I don't want to setup a middleware and send cookie info on every request
Where are you setting your cookies?

There's a bit of a snafu if you're setting a cookie in middleware and want to read it - you have to set the cookie in the middleware and then read it using headers().cookie() or something like that.
I don't have any middle ware..m setting it in a server action which triggers inside a useeffect. M checking for this cookie in page.tsx which is in app directory.
So your flow is this:

Load Page -> Server action triggered in useEffect (by user action/button?) -> server action response cookie is set -> user navigate to other page somehow -> read cookie.

And you expect the cookie value to be there, but somehow it is null/not present. I can check you're not setting maxAge of the cookie to 0 as that would make the cookie invalid immediately.
M setting maxAge to 3 months