Next.js Discord

Discord Forum

Error: `cookies` was called outside a request scope

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
I have a function verifySession() in a use server file that accesses cookies() and decrypts the JWT to if the user session is valid.

The verifySession() function is used in plenty of Data Access Layer files (files that have functions which perform DB queries using Prisma).

In the dev server, it works normally, but when building for production, I keep getting the error cookies was called outside a request scope in all the DAL files that use the verifySession() function.

Why weren't these errors happening in the dev server? How can I make them work while maintaing the code structure (i.e. not taking out that cookies() call to have it in a function that has a Request object?

Note: I'm following the same logic of verifySession() as this [Vercel example](https://github.com/vercel-labs/app-router-auth/blob/56ad0e514b6ba3046de5ad47567ac1c612adda20/app/auth/03-dal.ts), which also performs a cookies() call on in a file that doesn't have access to the Request object.

5 Replies

@gin is your verifySession inside a server action?
Sloth bearOP
yes it has "use server" in the beginning of the file, but it's not located in app/ (it's in another folder). and the file is not called actions.ts (not sure of that name is required)
@gin first check if u can get the cookie in your action and have verifySession accept the value
Sloth bearOP
Well everything actually works fine in the dev server, never even got this error. it only happens when doing a production build.
So in terms of it works or not, it def worked normally in the dev server.