NextAuth v5 req.auth Undefined with wrangler pages dev on Cloudflare Pages, Works with npm run dev
I'm using NextAuth v5 with Next.js 15 for authentication with JWT strategy. Everything works as expected when running the app locally using:
npm run dev
The req.auth object in my middleware is properly populated after login, and auth.user contains the expected user information.
When I run the app using:
wrangler pages dev
to emulate the Cloudflare Pages environment, I face this issue:
The authentication flow appears successful (cookies are set in the browser).
However, req.auth is undefined inside my Next.js middleware.ts.
Consequently, users are redirected to /login even after successful login.
my middleware
nextauth config
What I've Verified:
Cookies like __Host-authjs.csrf-token, authjs.session-token, etc., are present in both environments.
process.env.AUTH_SECRET is defined and logged correctly in both environments.
In npm run dev, I see additional nextauth.message in localStorage, but unsure if that's relevant.
Using JWT sessions, no database involved.
Login redirects appear to work, but req.auth stays undefined under wrangler pages dev.1 Reply
Recommended Steps to Troubleshoot:
Strictly verify AUTH_URL and AUTH_TRUST_HOST for wrangler pages dev and your Cloudflare Pages deployment. This is the most common fix.
Temporarily simplify your matcher in middleware.ts to something very basic like ["/"] to rule out any regex issues (though your current one looks standard).
Add console.log(request.headers) in your middleware to see what headers are being sent and if X-Forwarded-Host etc., are present.
If possible, create a minimal Next.js + NextAuth.js project from scratch with only the bare essentials and try deploying it to wrangler pages dev to isolate the problem. Cloudflare often provides templates or examples for Next.js and Auth.js.
Check NextAuth.js and Cloudflare Pages documentation/issues: There might be specific known issues or recommended configurations for your exact versions. Searching on GitHub issues for next-auth and cloudflare pages is often fruitful.