Skip to content

refactor(nextjs): factor runHandlerWithRequestState out of baseNextMiddleware#8368

Open
jacekradko wants to merge 1 commit intomainfrom
jacek/sdk-70-factor-middleware
Open

refactor(nextjs): factor runHandlerWithRequestState out of baseNextMiddleware#8368
jacekradko wants to merge 1 commit intomainfrom
jacek/sdk-70-factor-middleware

Conversation

@jacekradko
Copy link
Copy Markdown
Member

Summary

Groundwork for SDK-70. Pure refactor — no behavioral change.

  • @clerk/backend — exports a new createBootstrapSignedOutState helper from @clerk/backend/internal. Returns a synthetic UnauthenticatedState<'session_token'> without requiring a publishable key or an AuthenticateContext. Intended for framework integrations that need to run authorization logic before real Clerk keys are available (e.g. the Next.js keyless bootstrap window).
  • @clerk/nextjs — factors the post-authentication pipeline inside baseNextMiddleware (handler invocation, CSP, redirects, response decoration) into a private runHandlerWithRequestState helper. The authenticateRequest call and subsequent pipeline now live in a single, testable unit, making it possible for a follow-up to feed a synthesized RequestState into the same pipeline when there's no real publishable key yet.

Why split this PR?

The follow-up (SDK-70 proper) will flip keylessMiddleware's no-key branch to synthesize a signed-out state and run the user's middleware handler, closing a middleware-bypass window during the keyless bootstrap. That change is small on its own — most of the work is the plumbing to route a non-authenticateRequest-produced RequestState through the same post-auth pipeline. Landing the plumbing first keeps the behavioral change's diff small and reviewable.

Test plan

  • pnpm turbo build --filter=@clerk/backend --filter=@clerk/nextjs passes
  • pnpm --filter=@clerk/backend test — 1186/1186 pass (includes the updated exports.test.ts snapshot)
  • pnpm --filter=@clerk/nextjs test — 369 pass / 50 fail; all 50 failures are a pre-existing AbortSignal/createClerkRequest test-env issue that reproduces identically on main (unrelated to this refactor)
  • Manual smoke: keyless bootstrap still works end-to-end (no behavioral change expected since both call sites in baseNextMiddleware were preserved)

…ddleware

Extracts the post-authentication pipeline (handler invocation, CSP, redirects,
response decoration) into a private helper. Also adds createBootstrapSignedOutState
to @clerk/backend/internal for synthesizing a signed-out RequestState without a
publishable key — intended for framework integrations that must run authorization
logic before real Clerk keys are available (e.g. the Next.js keyless bootstrap
window).

Pure refactor — no behavioral change.
@vercel
Copy link
Copy Markdown

vercel bot commented Apr 21, 2026

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

Project Deployment Actions Updated (UTC)
clerk-js-sandbox Ready Ready Preview, Comment Apr 21, 2026 3:35am

Request Review

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Apr 21, 2026

🦋 Changeset detected

Latest commit: 98d26f7

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

This PR includes changesets to release 10 packages
Name Type
@clerk/backend Minor
@clerk/nextjs Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/hono Patch
@clerk/nuxt Patch
@clerk/react-router 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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 21, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 2d3a14c3-cb76-44c1-a6a4-91fd144159e3

📥 Commits

Reviewing files that changed from the base of the PR and between 683399a and 98d26f7.

📒 Files selected for processing (6)
  • .changeset/sdk-70-backend-bootstrap-state.md
  • .changeset/sdk-70-middleware-refactor.md
  • packages/backend/src/__tests__/exports.test.ts
  • packages/backend/src/internal.ts
  • packages/backend/src/tokens/authStatus.ts
  • packages/nextjs/src/server/clerkMiddleware.ts

📝 Walkthrough

Walkthrough

This pull request introduces a new createBootstrapSignedOutState helper function to the @clerk/backend package's internal API, which constructs a synthetic unauthenticated state without requiring a publishable key or authentication context. The helper is exported through the internal subpath and verified via export snapshot tests. Concurrently, the @clerk/nextjs middleware undergoes structural refactoring that extracts post-authentication request processing (including handler invocation, CSP handling, redirects, and response decoration) into a private runHandlerWithRequestState helper function, with the changeset documenting this as a behavioral no-op refactor.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Detailed analysis

Feature addition (backend):

  • New function createBootstrapSignedOutState in packages/backend/src/tokens/authStatus.ts (~46 lines) introduces logic to construct a synthetic UnauthenticatedState with sensible defaults, integrating with existing debug header utilities.
  • Supporting type BootstrapSignedOutParams defines the parameter shape with optional overrides.
  • Export surface updates in packages/backend/src/internal.ts and verification in snapshot tests (exports.test.ts).

Refactoring (nextjs):

  • The middleware refactoring in packages/nextjs/src/server/clerkMiddleware.ts (~156 lines changed) extracts a contiguous block of post-authentication logic into a new internal runHandlerWithRequestState helper.
  • Logic extraction is structural rather than algorithmic; verification should confirm that extracted code preserves original control flow, error handling, and state mutations.
  • New imports (AccountlessApplication, Logger, LoggerNoCommit) accompany the refactoring but appear to service only the newly extracted logic.

Review focus areas:

  • Verify that createBootstrapSignedOutState correctly synthesizes the unauthenticated state and that defaults align with expected keyless bootstrap behavior.
  • Confirm that the middleware extraction preserves request/response mutation ordering, especially around header propagation, redirect handling, and CSP generation.
  • Ensure extracted helper function maintains proper error boundaries and logging semantics from the original inline implementation.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main refactoring work: extracting runHandlerWithRequestState from baseNextMiddleware in @clerk/nextjs, which is the primary change in the changeset.
Description check ✅ Passed The description is directly related to the changeset, explaining the groundwork for SDK-70, detailing the new createBootstrapSignedOutState helper and the runHandlerWithRequestState refactoring with clear rationale.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Apr 21, 2026

Open in StackBlitz

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8368

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8368

@clerk/upgrade

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

@clerk/vue

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

commit: 98d26f7

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.

1 participant