Skip to content

Commit

Permalink
fix(nextjs): Avoid setting clerkUrl port for http(s) if protocol is set
Browse files Browse the repository at this point in the history
Issue: #1413
PR introducing issue: #1394
  • Loading branch information
dimkl committed Jun 26, 2023
1 parent 6fa6749 commit 0490217
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions packages/nextjs/src/server/authMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -361,18 +361,28 @@ How to resolve:
-> Make sure you are using the latest version of '@clerk/nextjs' and 'next'.
`;

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

const withNormalizedClerkUrl = (req: NextRequest): WithClerkUrl<NextRequest> => {
if (!TRUST_HOST) {
return Object.assign(req, { experimental_clerkUrl: req.nextUrl });
}

const clerkUrl = req.nextUrl.clone();
clerkUrl.protocol = getFirstValueFromHeader(req, constants.Headers.ForwardedProto) ?? clerkUrl.protocol;
clerkUrl.host = getFirstValueFromHeader(req, constants.Headers.ForwardedHost) ?? clerkUrl.host;
clerkUrl.port = getFirstValueFromHeader(req, constants.Headers.ForwardedPort) ?? clerkUrl.port;

const protocol = getFirstValueFromHeader(req, constants.Headers.ForwardedProto);
const host = getFirstValueFromHeader(req, constants.Headers.ForwardedHost);
const port = getFirstValueFromHeader(req, constants.Headers.ForwardedPort);

const isHttpRelatedProtocol = protocol && ['http', 'https'].includes(protocol);
const isNotHttpRelatedPort = port && !['80', '443'].includes(port);
if (isHttpRelatedProtocol && isNotHttpRelatedPort) {
clerkUrl.port = port;
}

clerkUrl.protocol = protocol ?? clerkUrl.protocol;
clerkUrl.host = host ?? clerkUrl.host;

return Object.assign(req, { experimental_clerkUrl: clerkUrl });
};

0 comments on commit 0490217

Please sign in to comment.