Hi everyone 👋
I’m running into a production-only auth issue with Next.js App Router + middleware + Better Auth.
Everything works perfectly in local dev, but in production users get redirected to /login even though the session cookie clearly exists.
🔍 Setup
Next.js (App Router)
Middleware (proxy.ts)
Better Auth (Google OAuth)
Deployed on Vercel
Domain:
https://www.flexnightlife.comCookie name in production:
__Secure-better-auth.session_token
✅ What Works
After Google login:
OAuth completes successfully
Cookie is created
In DevTools → Application → Cookies I see:
__Secure-better-auth.session_tokenDomain: www.flexnightlife.comPath: /Secure: trueHttpOnly: trueSameSite: LaxSo the session cookie definitely exists.
❌ The Problem
When navigating to:
/dashboard/organizationI get:
307 redirect → /loginIn Network tab I see:
Next-Router-Prefetch: 1Rsc: 1No Cookie header present in request
So middleware sees no cookie and redirects.
🧠 My Middleware
export function proxy(request: NextRequest) { const sessionCookie = request.cookies.get("better-auth.session_token") ?? request.cookies.get("_Secure-better-auth.session_token") ?? request.cookies.get("__Secure-better-auth.session_token") ?? request.cookies.getAll().find((c) => c.name.endsWith("better-auth.session_token") ); if (!sessionCookie?.value) { return NextResponse.redirect(new URL("/login", request.url)); } return NextResponse.next();}export const config = { matcher: ["/dashboard/:path*"],};I also tried skipping prefetch requests:
if (request.headers.get("next-router-prefetch") === "1") { return NextResponse.next();}Still not working.
⚠️ Important Observation
In production:
The prefetch request to
/dashboard/...does not include cookies.Middleware runs.
It redirects to
/login.Navigation ends up redirecting even though user is logged in.
In local dev this never happens.
🧩 Questions
Is this expected behavior for RSC prefetch requests in production?
Should middleware skip auth checks for RSC/prefetch?
Is this a known limitation of middleware + App Router?
Is there a better pattern for auth protection in App Router?
🎯 Expected Behavior
If user is authenticated (valid session cookie exists),
navigating to /dashboard should not redirect.
If anyone has run into this with:
Next.js 14+
Vercel
Better Auth / Auth.js / custom auth
App Router middleware
I’d really appreciate guidance 🙏
If you want, I can also give you:
A shorter Discord-style version
A StackOverflow-formatted version
Or a more technical deep-dive version for the Next.js repo
Just tell me where you're planning to post it.