🛑 Next.js 15 – “cookies inside use cache” Error in Layout Component
Hey everyone, I’m running into an issue in my Next.js 15 app when trying to fetch session data inside my DashboardLayout component.
I need to pass request headers to my getSession function, but I keep getting the following error about accessing dynamic data sources inside a cache scope. I’ve tried extracting the headers outside the function and passing them as arguments, but the issue persists.
Has anyone encountered this before? Any ideas on how to properly handle this while keeping caching?
Here’s my current code:
Here's the error:
8 Replies
hey! 🙂
still having this issue
The 'use cache' directive caches things on the server, so it can't be used with the headers and cookies functions as these will be different for each request. To keep the caching you can enable session cache in better auth https://www.better-auth.com/docs/concepts/session-management#session-caching
Session Management | Better Auth
Better Auth session management.
i have session cache enabled but still see that the session is being fetched from the database on every refresh. what could be failing?
There are four checks which have to pass for the data from cookie to be returned.
Possibilities are that:
- the session data cookie is absent or not able to be correctly parsed
- the cookieCache is disabled or the expiration time is set too low so the cookie has expired by the time it is read
Can you share your auth config file?
i used the example session cache config. maybe the session cookie is not being saved correctly.
i think i've solved it. could the session data cookie be failing to be saved for any reason?
[nextCookies(), admin()] @Netrifier
i thought it was supposed to be last in the list?
Your absolutely right, after looking at docs