Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nextjs): Avoid setting clerkUrl port when http(s) forwarded port and protocol is defined #1419

Merged
merged 1 commit into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/slow-needles-jam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/nextjs': patch
---

Resolve issue of appending :80 in urls when using CLERK_TRUST_HOST
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 host = getFirstValueFromHeader(req, constants.Headers.ForwardedHost);
const protocol = getFirstValueFromHeader(req, constants.Headers.ForwardedProto);
const port = getFirstValueFromHeader(req, constants.Headers.ForwardedPort);

const isHttpRelatedProtocol = protocol && ['http', 'https'].includes(protocol);
const isHttpRelatedPort = port && ['80', '443'].includes(port);
if (isHttpRelatedProtocol && isHttpRelatedPort) {
dimkl marked this conversation as resolved.
Show resolved Hide resolved
clerkUrl.port = '';
}

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

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