Skip to content

Commit

Permalink
fix(nextjs): Support using x-forwarded-* headers in req.nextUrl via env
Browse files Browse the repository at this point in the history
Introduced environment variable: CLERK_USE_X_FWD_HEADERS
Provide `"true"` value to enable this.

related NextJS issue:  vercel/next.js#37536
  • Loading branch information
dimkl committed Jun 20, 2023
1 parent 32ef330 commit 047a629
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/nice-kangaroos-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/nextjs': patch
---

Support non-Vercel platforms to override hostname of the url to fix the `localhost:3000` redirect from authMiddleware
21 changes: 19 additions & 2 deletions packages/nextjs/src/server/authMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ type BeforeAuthHandler = (
) => NextMiddlewareResult | Promise<NextMiddlewareResult> | false | Promise<false>;

type AfterAuthHandler = (
auth: AuthObject & { isPublicRoute: boolean },
auth: AuthObject & { isPublicRoute: boolean; isApiRoute: boolean },
req: NextRequest,
evt: NextFetchEvent,
) => NextMiddlewareResult | Promise<NextMiddlewareResult>;
Expand Down Expand Up @@ -134,6 +134,9 @@ const authMiddleware: AuthMiddleware = (...args: unknown[]) => {
logger.enable();
}

setClerkUrlInRequest(req);
const requestUrl = process.env.CLERK_USE_X_FWD_HEADERS !== 'true' ? req.clerkUrl : req.nextUrl;

logger.debug('URL debug', { url: req.nextUrl.href, method: req.method, headers: stringifyHeaders(req.headers) });
logger.debug('Options debug', { ...options, beforeAuth: !!beforeAuth, afterAuth: !!afterAuth });

Expand Down Expand Up @@ -215,7 +218,7 @@ const createDefaultAfterAuth = (
if (!auth.userId && !isPublicRoute(req) && isApiRoute(req)) {
return apiEndpointUnauthorizedNextResponse();
} else if (!auth.userId && !isPublicRoute(req)) {
return redirectToSignIn({ returnBackUrl: req.url });
return redirectToSignIn({ returnBackUrl: req.nextUrl.href });
}
return NextResponse.next();
};
Expand Down Expand Up @@ -332,3 +335,17 @@ A bug that may have already been fixed in the latest version of Clerk NextJS pac
How to resolve:
-> Make sure you are using the latest version of '@clerk/nextjs' and 'next'.
`;

const setClerkUrlInRequest = (req: NextRequest) => {
const clerkUrl = req.nextUrl.clone();
clerkUrl.protocol = getFirstValueFromHeader(req, 'x-forwarded-proto') ?? clerkUrl.protocol;
clerkUrl.host = getFirstValueFromHeader(req, 'x-forwarded-host') ?? clerkUrl.host;
clerkUrl.port = getFirstValueFromHeader(req, 'x-forwarded-port') ?? clerkUrl.port;

Object.assign(req, { clerkUrl });
};

const getFirstValueFromHeader = (req: NextRequest, key: string) => {
const value = req.headers.get(key);
return value?.split(',')[0];
};

0 comments on commit 047a629

Please sign in to comment.