-
Notifications
You must be signed in to change notification settings - Fork 374
feat(nextjs): Include additional headers for Next.js keyless app creation #6537
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
base: main
Are you sure you want to change the base?
feat(nextjs): Include additional headers for Next.js keyless app creation #6537
Conversation
🦋 Changeset detectedLatest commit: 0ad9831 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
The latest updates on your projects. Learn more about Vercel for GitHub.
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
📝 WalkthroughWalkthroughMetadataHeaders in packages/nextjs/src/server/keyless-custom-headers.ts was changed: userAgent is now required and new fields were added (port?, host, xHost, xPort, xProtocol, xClerkAuthStatus). collectKeylessMetadata now reads User-Agent (defaulting to "unknown user-agent"), process.env.PORT, and host / x-forwarded-port / x-forwarded-host / x-forwarded-proto / x-clerk-auth-status headers with fallbacks. formatMetadataHeaders conditionally emits additional Clerk-* headers (Clerk-Node-Port, Clerk-Client-Host, Clerk-X-Port, Clerk-X-Host, Clerk-X-Protocol, Clerk-Auth-Status) alongside Clerk-Client-User-Agent. A changeset was added and unit tests for collect/format behavior were introduced. Estimated code review effort🎯 3 (Moderate) | ⏱️ ~15 minutes Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the "Integrations" page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
⏰ 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). (11)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (5)
packages/nextjs/src/server/keyless-custom-headers.ts (5)
21-23
: Unnecessary await on headers(); remove await and eslint-disablenext/headers.headers() is synchronous. The await is a no-op and the eslint disable can be dropped. Keeping the function async is fine if you want to preserve its Promise return type, but the await here should go.
Apply:
-export async function collectKeylessMetadata(): Promise<MetadataHeaders> { - const headerStore = await headers(); // eslint-disable-line +export async function collectKeylessMetadata(): Promise<MetadataHeaders> { + const headerStore = headers();
28-34
: Nit: Normalize fallback values to token style (hyphenate) for easier parsing/searchingUsing space-separated phrases as sentinels can be brittle. Consider hyphenating to keep values single tokens.
Apply:
- userAgent: headerStore.get('User-Agent') ?? 'unknown user-agent', + userAgent: headerStore.get('User-Agent') ?? 'unknown-user-agent', - host: headerStore.get('host') ?? 'unknown host', + host: headerStore.get('host') ?? 'unknown-host', - xPort: headerStore.get('x-forwarded-port') ?? 'unknown x-forwarded-port', + xPort: headerStore.get('x-forwarded-port') ?? 'unknown-x-forwarded-port', - xHost: headerStore.get('x-forwarded-host') ?? 'unknown x-forwarded-host', + xHost: headerStore.get('x-forwarded-host') ?? 'unknown-x-forwarded-host', - xProtocol: headerStore.get('x-forwarded-proto') ?? 'unknown x-forwarded-proto', + xProtocol: headerStore.get('x-forwarded-proto') ?? 'unknown-x-forwarded-proto', - xClerkAuthStatus: headerStore.get('x-clerk-auth-status') ?? 'unknown x-clerk-auth-status', + xClerkAuthStatus: headerStore.get('x-clerk-auth-status') ?? 'unknown-x-clerk-auth-status',
52-54
: Avoid shadowing the imported headers() with a local const named headersHaving both the import named headers and a local const headers is confusing and easy to misuse. Rename the local variable.
Apply:
-export function formatMetadataHeaders(metadata: MetadataHeaders): Headers { - const headers = new Headers(); +export function formatMetadataHeaders(metadata: MetadataHeaders): Headers { + const outHeaders = new Headers();And replace all subsequent headers.set(...) and return headers with outHeaders. For convenience:
- if (metadata.nodeVersion) { - headers.set('Clerk-Node-Version', metadata.nodeVersion); + if (metadata.nodeVersion) { + outHeaders.set('Clerk-Node-Version', metadata.nodeVersion); } ... - return headers; + return outHeaders;
18-21
: Public API JSDoc could be more complete (params/returns and field descriptions)Both exported functions are public API in a package; add proper JSDoc tags to satisfy the guideline and help consumers.
Apply:
-/** - * Collects metadata from the environment and request headers - */ +/** + * Collects metadata from the environment and incoming request headers. + * + * @returns A complete set of keyless metadata with fallbacks for missing values. + */-/** - * Converts metadata to HTTP headers - */ +/** + * Converts metadata to HTTP headers for forwarding to Clerk APIs. + * + * @param metadata - The collected metadata (see MetadataHeaders). + * @returns Headers ready to be passed to fetch/init. + */Also applies to: 49-52
71-94
: Redundant guards for required fields (optional)Given the interface now makes userAgent, host, xHost, xPort, xProtocol, xClerkAuthStatus required (and collectKeylessMetadata always sets them), the if checks are effectively always true. You can set them unconditionally to simplify.
Example:
- if (metadata.userAgent) { - headers.set('Clerk-Client-User-Agent', metadata.userAgent); - } + headers.set('Clerk-Client-User-Agent', metadata.userAgent);Repeat for host/xHost/xPort/xProtocol/xClerkAuthStatus.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/nextjs/src/server/keyless-custom-headers.ts
(3 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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/nextjs/src/server/keyless-custom-headers.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/nextjs/src/server/keyless-custom-headers.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/nextjs/src/server/keyless-custom-headers.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/nextjs/src/server/keyless-custom-headers.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/nextjs/src/server/keyless-custom-headers.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/nextjs/src/server/keyless-custom-headers.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/nextjs/src/server/keyless-custom-headers.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). (26)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (tanstack-react-router, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Static analysis
- GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
packages/nextjs/src/server/keyless-custom-headers.ts (2)
1-2
: Good: Server-only module correctly markedThe "use server" directive is appropriate here and required for next/headers usage.
5-16
: The interfaceMetadataHeaders
is only used internally by thecollectKeylessMetadata
andformatMetadataHeaders
exports, and there are no external call sites manually constructing it. Since downstream consumers don’t directly import or buildMetadataHeaders
themselves, making the new fields required poses no breaking risk. Keeping the fields required also enforces correctness (you always supply the necessary headers). Exporting the interface isn’t needed unless you have an explicit use case for consumers to reference its shape.
7401a01
to
c623ef6
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Nitpick comments (3)
packages/nextjs/src/__tests__/keyless-custom-headers.test.ts (3)
17-46
: Simplify the module mock: return a Headers-like object directlyYou can reduce boilerplate by returning the default mock bag directly and override via
mockResolvedValue
where needed. This keeps the default path closer to realHeaders
behavior and makes per-test overrides explicit.-vi.mock('next/headers', () => ({ - headers: vi.fn(() => ({ - get: vi.fn((name: string) => { - // Return mock values for headers used in keyless-custom-headers.ts - return defaultMockHeaders.get(name); - }), - has: vi.fn((name: string) => { - return defaultMockHeaders.has(name); - }), - forEach: vi.fn((callback: (value: string, key: string) => void) => { - defaultMockHeaders.forEach(callback); - }), - entries: function* () { - const entries: [string, string][] = []; - defaultMockHeaders.forEach((value, key) => entries.push([key, value])); - for (const entry of entries) yield entry; - }, - keys: function* () { - const keys: string[] = []; - defaultMockHeaders.forEach((_, key) => keys.push(key)); - for (const key of keys) yield key; - }, - values: function* () { - const values: string[] = []; - defaultMockHeaders.forEach(value => values.push(value)); - for (const value of values) yield value; - }, - })), -})); +vi.mock('next/headers', () => ({ + headers: vi.fn(async () => defaultMockHeaders), +}));Note: This pairs well with the per-test
mockHeaders.mockReset()
andmockHeaders.mockImplementation(...)
from the other suggestion.
100-103
: Prefer vi.resetAllMocks over vi.restoreAllMocks in afterEach when only mocks are in play
vi.restoreAllMocks
mainly targets spies and restores originals. In a pure module-mocking setup,vi.resetAllMocks
clears call history and mock implementations. If you keeprestoreAllMocks
, ensure you’re not unintentionally restoring module state that tests depend on. At minimum, pair withmockHeaders.mockReset()
in beforeEach (as suggested).
1-16
: Ensure global Headers is available in the Vitest environmentThese tests instantiate
new Headers(...)
. In Node <18 or custom Vitest environments,Headers
may be undefined without Undici polyfill. If your CI runs in such environments, explicitly import or polyfillHeaders
to avoid brittle test environments.Would you like me to add a small setup file that imports
undici
and setsglobalThis.Headers = Headers
if missing?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/nextjs/src/__tests__/keyless-custom-headers.test.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/nextjs/src/__tests__/keyless-custom-headers.test.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/nextjs/src/__tests__/keyless-custom-headers.test.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/nextjs/src/__tests__/keyless-custom-headers.test.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/nextjs/src/__tests__/keyless-custom-headers.test.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/nextjs/src/__tests__/keyless-custom-headers.test.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/nextjs/src/__tests__/keyless-custom-headers.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/nextjs/src/__tests__/keyless-custom-headers.test.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/nextjs/src/__tests__/keyless-custom-headers.test.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/nextjs/src/__tests__/keyless-custom-headers.test.ts
🧬 Code Graph Analysis (1)
packages/nextjs/src/__tests__/keyless-custom-headers.test.ts (1)
packages/nextjs/src/server/keyless-custom-headers.ts (2)
formatMetadataHeaders
(52-96)collectKeylessMetadata
(21-36)
⏰ 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). (5)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/nextjs/src/__tests__/keyless-custom-headers.test.ts (2)
354-379
: Good coverage of process.title failure pathGracefully handling exceptions from
process.title
and assertingnextVersion
is undefined makes the behavior explicit and resilient.
405-459
: End-to-end pipeline test is solidValidates that collected metadata maps exactly to formatted Clerk-* headers, including the new x-* fields. This protects the primary feature added by the PR.
5dc1db7
to
3d04140
Compare
c6c15a4
to
f92c729
Compare
f92c729
to
ccb1f69
Compare
ccb1f69
to
a7b6ba6
Compare
a7b6ba6
to
5b37f74
Compare
…r-keyless-app-creation-post
…r-keyless-app-creation-post
…r-keyless-app-creation-post
…r-keyless-app-creation-post
…r-keyless-app-creation-post
Description
To help us debug why keyless applications are failing to make certain API requests, this PR forwards the port, host, and custom x headers with POST requests to create keyless app instances. There are fallback values for these headers should they not exist.
This PR also adds a fallback value if the user-agent header does not exist.
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Documentation
Tests
Chores