Danny
Danny2mo ago

Convex Auth + Next.js headers error

Hiya, i'm trying to deploy a Next.js + Convex (auth), but am getting the error attached. It's definitely related to my middleware in some capacity. Here's my middleware file:
import {
convexAuthNextjsMiddleware,
createRouteMatcher,
nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server";

const isSignInPage = createRouteMatcher(["/signin"]);

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

export const config = {
// The following matcher runs middleware on all routes
// except static assets.
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
import {
convexAuthNextjsMiddleware,
createRouteMatcher,
nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server";

const isSignInPage = createRouteMatcher(["/signin"]);

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

export const config = {
// The following matcher runs middleware on all routes
// except static assets.
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
It also looks like a lot of other people are experiencing the same issue: https://github.com/get-convex/convex-auth/issues/120
GitHub
Error: headers was called outside a request scope. · Issue #120 ...
The issue appears when using SSA in Next JS Runtime: Bun version 1.1.34 Package version: "convex": "^1.17.0" "@auth/core": "0.36.0" "@convex-dev/auth&qu...
No description
2 Replies
erquhart
erquhart2mo ago
Looking at this The hard part here is not being able to reproduce it. Can you provide a repo that has this issue? What I can say is that convexAuthNextJsMiddleware() is a function that only returns a function - all use of headers happens inside that returned function, which Next must call and pass a request into. This is a request context where headers can be used. So something unexpected is happening when this occurs. But yeah, I haven't been able to repro this.
Danny
DannyOP2mo ago
Forgot to mention but this only seems to trigger when running a production build, it works fine in development

Did you find this page helpful?