Skip to content

Conversation

@ItalyPaleAle
Copy link

@ItalyPaleAle ItalyPaleAle commented Oct 23, 2025

Description

When Clerk is served behind a proxy, it uses the X-Forwarded-Proto and X-Forwarded-Host headers to determine the proto and host of the request, and redirect the client to the right place, as per docs.

However, we are dealing with a situation where because of other proxies in-between, we cannot leverage the X-Forwarded-Host header, and that makes Clerk not usable in this environment.

I am proposing adding two new environmental variables which allow overriding the name of the header that Clerk uses to perform lookups:

  • CLERK_PROXY_FORWARDED_PROTO_HEADER
  • CLERK_PROXY_FORWARDED_HOST_HEADER

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • N/A (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Allow configuring which proxy headers are used to determine request protocol and host via environment settings, preserving default behavior for standard proxies.
  • Tests

    • Added tests covering custom proxy header configurations to ensure correct origin detection across proxy setups.

@changeset-bot
Copy link

changeset-bot bot commented Oct 23, 2025

🦋 Changeset detected

Latest commit: 69383d8

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel
Copy link

vercel bot commented Oct 23, 2025

@ItalyPaleAle is attempting to deploy a commit to the Clerk Production Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2025

Walkthrough

Adds environment-variable overrides for the header names used to detect forwarded protocol and host in proxied requests (CLERK_PROXY_FORWARDED_PROTO_HEADER, CLERK_PROXY_FORWARDED_HOST_HEADER), preserving previous defaults.

Changes

Cohort / File(s) Summary
Implementation
packages/backend/src/tokens/clerkRequest.ts
Replaces hardcoded forwarded header lookups with values read from CLERK_PROXY_FORWARDED_PROTO_HEADER and CLERK_PROXY_FORWARDED_HOST_HEADER, falling back to original header names; origin computation uses these lookups.
Tests
packages/backend/src/tokens/__tests__/clerkRequest.test.ts
Adds a test that sets the environment overrides, supplies custom forwarded headers on a request, and asserts the constructed Clerk URL uses the overridden proto and host.
Changelog
.changeset/clever-wombats-look.md
Adds changeset entry documenting the minor version update and the new support for custom forwarded header names.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Proxy
  participant App as clerkRequest
  note right of App #E6F7FF: reads env overrides\nor uses defaults
  Client->>Proxy: HTTP request (original host/proto)
  Proxy->>App: proxied request with headers
  App->>App: read CLERK_PROXY_FORWARDED_PROTO_HEADER\nand CLERK_PROXY_FORWARDED_HOST_HEADER (or defaults)
  App->>App: extract forwarded proto/host from headers
  App->>App: compute origin (proto + host)
  App->>Clerk: construct Clerk URL using computed origin
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I sniff the headers, hop and pick,
Env-vars tell me which to pick,
Proto and host, now named anew,
I stitch the origin, quick as dew,
A tiny change — a happier trick. 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat(backend): Allow reading proto and host for proxied requests from a custom header" directly and accurately describes the main change in the changeset. The PR introduces environment variables to override the hardcoded X-Forwarded-Proto and X-Forwarded-Host header names, allowing Clerk to read protocol and host information from custom headers when deployed behind proxies. The title is concise, clear, and specific enough that a teammate scanning history would immediately understand the primary change without being vague or generic. It appropriately omits unnecessary implementation details like specific environment variable names, which is expected in a high-level title.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/backend/src/tokens/__tests__/clerkRequest.test.ts (1)

102-131: Consider adding edge case tests.

While the current test covers the happy path, consider adding tests for:

  • Empty string environment variables: CLERK_PROXY_FORWARDED_PROTO_HEADER=""
  • Whitespace-only values
  • Invalid header names (to document expected behavior)

This would help ensure robust handling of misconfigured environment variables.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 25f54f6 and 8c66330.

📒 Files selected for processing (3)
  • .changeset/clever-wombats-look.md (1 hunks)
  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts (1 hunks)
  • packages/backend/src/tokens/clerkRequest.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
  • packages/backend/src/tokens/clerkRequest.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
  • packages/backend/src/tokens/clerkRequest.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
  • packages/backend/src/tokens/clerkRequest.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
  • packages/backend/src/tokens/clerkRequest.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
  • packages/backend/src/tokens/clerkRequest.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
  • packages/backend/src/tokens/clerkRequest.ts
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/backend/src/tokens/__tests__/clerkRequest.test.ts
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/clever-wombats-look.md
🧬 Code graph analysis (1)
packages/backend/src/tokens/__tests__/clerkRequest.test.ts (1)
packages/backend/src/tokens/clerkRequest.ts (1)
  • createClerkRequest (89-91)
🔇 Additional comments (2)
.changeset/clever-wombats-look.md (1)

1-5: LGTM!

The changeset correctly documents the new feature with an appropriate minor version bump.

packages/backend/src/tokens/__tests__/clerkRequest.test.ts (1)

102-131: Excellent test structure and cleanup!

The test properly saves, modifies, and restores environment variables with appropriate handling for both defined and undefined original values. The use of try-finally ensures cleanup even if assertions fail.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/backend/src/tokens/clerkRequest.ts (1)

51-60: LGTM! Empty string handling properly addressed.

The switch from ?? to || correctly handles empty string environment variables by falling back to the default constants. The implementation is clean and maintains backward compatibility.


Optional: Consider trimming whitespace from environment variables.

While the current implementation handles empty strings correctly, whitespace-only values (e.g., " ") would still be treated as valid header names. If you want to be more defensive, you could trim and validate the environment variables:

-    const forwardedProto = req.headers.get(
-      process.env.CLERK_PROXY_FORWARDED_PROTO_HEADER || constants.Headers.ForwardedProto,
-    );
-    const forwardedHost = req.headers.get(
-      process.env.CLERK_PROXY_FORWARDED_HOST_HEADER || constants.Headers.ForwardedHost,
-    );
+    const protoHeader = process.env.CLERK_PROXY_FORWARDED_PROTO_HEADER?.trim() || constants.Headers.ForwardedProto;
+    const hostHeader = process.env.CLERK_PROXY_FORWARDED_HOST_HEADER?.trim() || constants.Headers.ForwardedHost;
+    
+    const forwardedProto = req.headers.get(protoHeader);
+    const forwardedHost = req.headers.get(hostHeader);

However, since this is an advanced configuration setting, the current approach is reasonable.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8c66330 and 69383d8.

📒 Files selected for processing (1)
  • packages/backend/src/tokens/clerkRequest.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/backend/src/tokens/clerkRequest.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/clerkRequest.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/backend/src/tokens/clerkRequest.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: semgrep-cloud-platform/scan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants