NextJS Auth Check
Hey! Iâm using Better Auth with Next.js and Iâm a bit confused about the recommended pattern for session checks.
In the middleware Iâm following the docs and doing:
const session = getSessionCookie(request);
As far as I understand, this only checks if the cookie exists, not whether the session is actually valid in the database.
My current behavior:
My questions:
Any small example or clarification would be really helpful, thanks! @Better Auth
In the middleware Iâm following the docs and doing:
const session = getSessionCookie(request);
As far as I understand, this only checks if the cookie exists, not whether the session is actually valid in the database.
My current behavior:
- The middleware sees the cookie and assumes Iâm logged in, so it allows me to access /app.
- Inside /app I do the real session check (e.g. getSession()), which correctly detects that Iâm not actually logged in anymore and redirects me to /login.
- But in the middleware I also have logic like if (session && pathname === '/login') redirect('/app'), so with a stale cookie I end up in an infinite redirect loop between /app and /login.
My questions:
- Whatâs the recommended best practice in this situation where almost everything is private?
- Should the middleware:
-- only use getSessionCookie to block access to /app when the cookie is missing,
-- but never redirect away from /login based solely on the presence of the cookie? - And then, inside /app (e.g. in the layout), should I call getSession() (or equivalent), and if the session is invalid:
-- clear the session cookie / sign out,
-- and then redirect back to /login, to avoid redirect loops with stale cookies?
Any small example or clarification would be really helpful, thanks! @Better Auth