I have a Next.js 15.3.2 application using Auth.js version 5 for user authentication with JWT tokens. When I test my app locally with the standard development server using npm run dev, everything works perfectly fine. The authentication object is available in my middleware and contains all the user data I need.
However, when I try to test the same application using wrangler pages dev to simulate the Cloudflare Pages environment, I run into a strange problem. The login process seems to work correctly and I can see the authentication cookies being created in the browser, but inside my middleware file, the auth property on the request object comes back as null or undefined.
This causes my middleware to think the user is not logged in, so it keeps redirecting them back to the login page even though they successfully authenticated.
Here’s my middleware setup:
import { authHandler } from "@/lib/authentication";
export default authHandler((request) => {
console.log("User data:", request.auth?.user);
console.log("Secret key:", process.env.AUTH_SECRET);
if (!request.auth && request.nextUrl.pathname !== "/signin") {
return Response.redirect(new URL("/signin", request.nextUrl));
}
});
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
And here’s my Auth.js configuration:
export const authHandler = NextAuth({
providers: [/*my providers*/],
secret: process.env.AUTH_SECRET,
session: { strategy: 'jwt' },
callbacks: {
async authorized({ auth, request }) {
console.log("Current user:", auth?.user);
console.log("Secret value:", process.env.AUTH_SECRET);
return !!auth?.user;
},
},
experimental: {
runtime: 'edge',
},
});
I’ve checked that all the authentication cookies are present in both environments, and the environment variables are loaded correctly. I’m using the latest versions of both wrangler and Auth.js.
Why would the authentication data be available in regular Next.js development but not when running through wrangler? Do I need special configuration for Cloudflare’s runtime environment?