SthapS
Convex Community7mo ago
8 replies
Sthap

Convex Auth Middleware Works in Dev, Fails in Production with headers Error

Hi, I'm trying to get my web app to production with nextjs, bun, convex but I've encountered this runtime error in logs.

Error: headers was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context

I think this caused by nextjs middleware.

What I've Confirmed:

My CONVEX_URL and CONVEX_DEPLOYMENT_KEYenvironment variables are set correctly in my production environment's settings.
I have run npx convex deploy and the production site is configured to use the production Convex URL.
The code uses the modern ConvexAuth pattern as recommended in the docs.

here's my middleware code if you're wondering
import {
  convexAuthNextjsMiddleware,
  createRouteMatcher,
  nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server";

const isSignInPage = createRouteMatcher(["/signin"]);
const isProtectedRoute = createRouteMatcher(["/", "/server", "/dashboard(.*)"]);

export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
  if (isSignInPage(request) && (await convexAuth.isAuthenticated())) {
    return nextjsMiddlewareRedirect(request, "/");
  }
  if (isProtectedRoute(request) && !(await convexAuth.isAuthenticated())) {
    return nextjsMiddlewareRedirect(request, "/signin");
  }
});

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
}


next:15.2.3
convex:^1.23.0
@convex-dev/auth:^0.0.81
image.png
Was this page helpful?