Skip to content

Conversation

@wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Oct 27, 2025

Description

This PR allows manually overriding options being passed to authenticateRequest() in React Router's clerkMiddleware()

Fixes #7073

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (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

  • Bug Fixes
    • Fixed an issue where manually specified middleware configuration options were not being properly passed through and respected during request processing.

@changeset-bot
Copy link

changeset-bot bot commented Oct 27, 2025

🦋 Changeset detected

Latest commit: d9f972c

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

This PR includes changesets to release 1 package
Name Type
@clerk/react-router 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 27, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Oct 27, 2025 4:16pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 27, 2025

Walkthrough

A patch release for @clerk/react-router fixes a bug where manually specified middleware options (keys, URLs, domain settings) were not being passed to authenticateRequest. The implementation now forwards all relevant options including publishableKey, secretKey, apiUrl, proxyUrl, and other configuration to the authentication request handler.

Changes

Cohort / File(s) Summary
Changeset
.changeset/purple-peas-shave.md
Documents patch release with bug fix: middleware now respects manually specified options
Test Updates
packages/react-router/src/server/__tests__/clerkMiddleware.test.ts
Expanded expected authenticateRequest parameters to include apiUrl, jwtKey, proxyUrl, isSatellite, domain, machineSecretKey, and publishableKey assertions
Middleware Implementation
packages/react-router/src/server/clerkMiddleware.ts
Refactored to pass all necessary options (apiUrl, secretKey, jwtKey, proxyUrl, isSatellite, domain, publishableKey, machineSecretKey, audience, authorizedParties, organizationSyncOptions, signInUrl, signUpUrl, afterSignInUrl, afterSignUpUrl) and acceptsToken: 'any' to authenticateRequest

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • The changes follow a consistent pattern: expanding parameter passing from middleware to authenticateRequest
  • Test expectations are straightforward assertions of additional fields
  • Core control flow and public API remain unchanged
  • Primary focus: ensuring configuration options are no longer dropped during middleware execution

Poem

🐰 Through the middleware's gentle hop,
Options flow without a stop,
Keys and configs find their way,
No more lost along the path today!
A patch to make the routing right, 🛣️

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "fix(react-router): Respect manual configuration options in middleware" clearly and accurately describes the main change in the changeset. The changeset file explicitly mentions this is a bug fix where "manually specified options in the middleware are now respected," which directly aligns with the title. The title is concise, specific, and conveys the primary purpose of the PR without ambiguity or unnecessary details.
Linked Issues Check ✅ Passed The code changes directly address the requirement in issue #7073 to respect manually specified configuration options (particularly publishableKey and secretKey) in the middleware. The refactored clerkMiddleware.ts now passes a comprehensive set of options to authenticateRequest, including the previously omitted secretKey and publishableKey fields. The corresponding test updates verify that these fields are now being passed correctly, confirming the fix is implemented as intended to resolve the issue where manually provided keys were being ignored.
Out of Scope Changes Check ✅ Passed All changes in the pull request are directly scoped to addressing issue #7073. The modifications to clerkMiddleware.ts fix the core issue by passing manually specified options to authenticateRequest. The test file updates align with the implementation changes to verify the fix works correctly. The changeset file is a standard release management artifact documenting the bug fix. There are no unrelated changes or modifications outside the stated objectives of respecting manually specified configuration options in the middleware.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch rob/fix-react-router-7073

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

@wobsoriano wobsoriano changed the title fix(react-router): Allow overriding of options in middleware fix(react-router): Respect manual configuration options in middleware Oct 27, 2025
@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 27, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@7079

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@7079

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@7079

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@7079

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@7079

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@7079

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@7079

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@7079

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@7079

@clerk/express

npm i https://pkg.pr.new/@clerk/express@7079

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@7079

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@7079

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@7079

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@7079

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@7079

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@7079

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@7079

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@7079

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@7079

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@7079

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@7079

@clerk/types

npm i https://pkg.pr.new/@clerk/types@7079

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@7079

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@7079

commit: d9f972c

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/react-router/src/server/__tests__/clerkMiddleware.test.ts (1)

67-83: Test expectations updated correctly, but consider adding coverage for the bug fix.

The test expectations now match the new authenticateRequest signature. However, there's no test case that specifically validates the bug fix - i.e., that manually provided options (especially keys) are actually passed through to authenticateRequest.

Consider adding a test case like this:

it('should pass manually specified keys to authenticateRequest', async () => {
  const mockRequestState = {
    status: AuthStatus.SignedIn,
    headers: new Headers(),
    toAuth: vi.fn().mockReturnValue({ userId: 'user_xxx', tokenType: TokenType.SessionToken }),
  };

  const mockAuthenticateRequest = vi.fn().mockResolvedValue(mockRequestState);
  mockClerkClient.mockReturnValue({
    authenticateRequest: mockAuthenticateRequest,
  } as unknown as ClerkClient);

  const customOptions: ClerkMiddlewareOptions = {
    publishableKey: 'pk_custom_...',
    secretKey: 'sk_custom_...',
  };

  mockLoadOptions.mockReturnValue({
    ...mockLoadOptions.mock.results[0].value,
    publishableKey: 'pk_custom_...',
    secretKey: 'sk_custom_...',
  } as ReturnType<typeof loadOptions>);

  const middleware = clerkMiddleware(customOptions);
  const args = {
    request: new Request('http://clerk.com'),
    context: mockContext,
  } as LoaderFunctionArgs;

  const mockResponse = new Response('OK');
  mockNext.mockResolvedValue(mockResponse);

  await middleware(args, mockNext);

  // Verify custom keys are passed through
  expect(mockAuthenticateRequest).toHaveBeenCalledWith(
    expect.any(Object),
    expect.objectContaining({
      publishableKey: 'pk_custom_...',
      secretKey: 'sk_custom_...',
    })
  );
});
📜 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 754b47b and d9f972c.

📒 Files selected for processing (3)
  • .changeset/purple-peas-shave.md (1 hunks)
  • packages/react-router/src/server/__tests__/clerkMiddleware.test.ts (1 hunks)
  • packages/react-router/src/server/clerkMiddleware.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/react-router/src/server/__tests__/clerkMiddleware.test.ts
  • packages/react-router/src/server/clerkMiddleware.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/react-router/src/server/__tests__/clerkMiddleware.test.ts
  • packages/react-router/src/server/clerkMiddleware.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/react-router/src/server/__tests__/clerkMiddleware.test.ts
  • packages/react-router/src/server/clerkMiddleware.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/react-router/src/server/__tests__/clerkMiddleware.test.ts
  • packages/react-router/src/server/clerkMiddleware.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/react-router/src/server/__tests__/clerkMiddleware.test.ts
  • packages/react-router/src/server/clerkMiddleware.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/react-router/src/server/__tests__/clerkMiddleware.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/react-router/src/server/__tests__/clerkMiddleware.test.ts
  • packages/react-router/src/server/clerkMiddleware.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/react-router/src/server/__tests__/clerkMiddleware.test.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/purple-peas-shave.md
🧬 Code graph analysis (1)
packages/react-router/src/server/clerkMiddleware.ts (1)
packages/react-router/src/server/clerkClient.ts (1)
  • clerkClient (5-21)
🪛 LanguageTool
.changeset/purple-peas-shave.md

[style] ~4-~4: Consider using a different verb for a more formal wording.
Context: --- "@clerk/react-router": patch --- Fixed an issue where manually specified optio...

(FIX_RESOLVE)

🔇 Additional comments (3)
packages/react-router/src/server/clerkMiddleware.ts (2)

58-75: Correctly forwards all options to authenticateRequest.

The implementation properly passes all destructured options to authenticateRequest, ensuring that manually specified configuration (keys, URLs, etc.) is respected. This is the core fix for issue #7073.


37-56: Verification confirms the destructuring fix is correct.

All 15 destructured properties from loadedOptions are correctly passed to authenticateRequest(). The type definition confirms organizationSyncOptions is a valid AuthenticateRequestOptions property, and the implementation matches the pattern used in other framework integrations (express, remix, nuxt).

The fix properly addresses the reported issue where manually specified options (keys, URLs, organization settings) were being ignored by ensuring they're extracted and passed through to the authentication handler.

.changeset/purple-peas-shave.md (1)

1-5: Changeset correctly documents the patch fix.

The changeset properly specifies a patch version bump and clearly describes the bug fix. The static analysis suggestion to use a different verb is a false positive - "Fixed" is standard terminology for bug fix changesets.

@wobsoriano wobsoriano merged commit 526f708 into main Oct 27, 2025
49 checks passed
@wobsoriano wobsoriano deleted the rob/fix-react-router-7073 branch October 27, 2025 17:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Keys not being used in @clerk/react-router middleware

4 participants