Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Dec 27, 2025

Description

In an app that has PPRenabled when using await auth() in an API route we see the following pre-rendering error during build:

web:build: ✓ Compiled successfully in 14.8s
web:build:   Skipping validation of types
web:build: ✓ Collecting page data using 11 workers in 1514.3ms 
Error fetching task events: Error: Clerk: auth(), currentUser() and clerkClient(), are only supported in App Router (/app directory).
web:build: If you're using /pages, try getAuth() instead.
web:build: Original error: Error: During prerendering, `headers()` rejects when the prerender is complete. Typically these errors are handled by React but if you move `headers()` to a different context by using `setTimeout`, `after`, or similar functions you may observe this error and you should handle it in that context. This occurred at route "/api/tasks/events".
web:build:     at async n (src/lib/api-permissions.ts:21:29)
web:build:     at async w (src/app/api/tasks/events/route.ts:13:24)
web:build:   19 |   orgId: string | null | undefined;
web:build:   20 | }> {
web:build: > 21 |   const { userId, orgId } = await auth();
web:build:      |                             ^
web:build:   22 |
web:build:   23 |   if (!userId) {
web:build:   24 |     throw NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
web:build: ✓ Generating static pages using 11 workers (95/95) in 572.0ms
web:build: ✓ Finalizing page optimization in 885.1ms 
web:build: 
web:build: Route (app)
web:build: ┌ ◐ /
web:build: ├ ◐ /_not-found
web:build: ├ ƒ /.well-known/oauth-authorization-server
web:build: ├ ƒ /.well-known/oauth-protected-resource/mcp
web:build: ├ ƒ /api/tasks
web:build: ├ ƒ /api/tasks/events
web:build: ├ ◐ /settings
web:build: 
web:build: 
web:build: ƒ Proxy (Middleware)
web:build: 
web:build: ○  (Static)             prerendered as static content
web:build: ◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content
web:build: ƒ  (Dynamic)            server-rendered on demand
web:build: 

Adding await connection() to auth() to signal to next.js that the route is not eligible for PPR.

Related: USER-4044

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

    • Prevents prerendering failures when using auth() with Next.js Cache Components and surfaces clearer errors for incompatible cache/use-cache scenarios, including a runtime guard for Next.js 16.
  • Tests

    • Added unit tests covering prerendering bailout and cache-related error detection.
  • Chores

    • Added a changeset entry documenting a patch release.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Dec 27, 2025

🦋 Changeset detected

Latest commit: 564e8a0

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

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

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

1 Skipped Deployment
Project Deployment Review Updated (UTC)
clerk-js-sandbox Skipped Skipped Jan 7, 2026 2:56am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 27, 2025

📝 Walkthrough

Walkthrough

A runtime guard was added to auth() to dynamically import and invoke Next.js 16's connection() to opt out of prerendering when available, with prerender bailout errors rethrown. A new isNextjsUseCacheError helper (precompiled regexes) was introduced and integrated into request-building and error handling to detect and propagate Next.js "use cache" errors. Prerendering bailout detection was extended to cover headers() rejections. Unit tests for the error predicates were added and a patch changeset was created.

Pre-merge checks

❌ Failed checks (1 warning, 1 inconclusive)
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.
Title check ❓ Inconclusive The title refers to PPR (Partial Pre-Rendering) and auth(), but the primary change focuses on Next.js 16 cache components support, not PPR specifically. Consider clarifying the title to reflect the core objective: supporting Next.js cache components with auth(), as PPR is one aspect of this broader support.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR implements baseline Next.js cache components support by adding connection() call and error handling for use-cache scenarios, directly meeting USER-4044 requirements.
Out of Scope Changes check ✅ Passed All changes are focused on supporting cache components and preventing errors with auth(): connection() guard, use-cache error detection, and appropriate error handling.

📜 Recent review details

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

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 e11aed5 and 564e8a0.

📒 Files selected for processing (2)
  • packages/nextjs/src/app-router/server/__tests__/utils.test.ts
  • packages/nextjs/src/app-router/server/utils.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nextjs/src/app-router/server/tests/utils.test.ts
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

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

All code must pass ESLint checks with the project's configuration

Files:

  • packages/nextjs/src/app-router/server/utils.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/nextjs/src/app-router/server/utils.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/nextjs/src/app-router/server/utils.ts
**/*.{ts,tsx,js,jsx}

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

Follow established naming conventions (PascalCase for components, camelCase for variables)

Files:

  • packages/nextjs/src/app-router/server/utils.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/nextjs/src/app-router/server/utils.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/nextjs/src/app-router/server/utils.ts
**/*.{ts,tsx}

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

**/*.{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
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
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 in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • packages/nextjs/src/app-router/server/utils.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/nextjs/src/app-router/server/utils.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/nextjs/src/app-router/server/utils.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.

**/*: Only comment on issues that would block merging, ignore minor or stylistic concerns.
Restrict feedback to errors, security risks, or functionality-breaking problems.
Do not post comments on code style, formatting, or non-critical improvements.
Keep reviews short: flag only issues that make the PR unsafe to merge.
Group similar issues into a single comment instead of posting multiple notes.
Skip repetition: if a pattern repeats, mention it once at a summary level only.
Do not add general suggestions, focus strictly on merge-blocking concerns.
If there are no critical problems, respond with minimal approval (e.g., 'Looks good'). Do not add additional review.
Avoid line-by-line commentary unless it highlights a critical bug or security hole.
Highlight only issues that could cause runtime errors, data loss, or severe maintainability issues.
Ignore minor optimization opportunities, focus solely on correctness and safety.
Provide a top-level summary of critical blockers rather than detailed per-line notes.
Comment only when the issue must be resolved before merge, otherwise remain silent.
When in doubt, err on the side of fewer comments, brevity and blocking issues only.
Avoid posting any refactoring issues.

Files:

  • packages/nextjs/src/app-router/server/utils.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). (25)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/nextjs/src/app-router/server/utils.ts (1)

1-135: Looks good.

The implementation correctly handles Next.js prerendering bailout and "use cache" error scenarios. The pre-compiled regex patterns, explicit return type, and comprehensive error message with usage guidance are well done.


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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 27, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

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

@clerk/upgrade

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

@clerk/vue

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

commit: 564e8a0

… Components

Call connection() in auth() before accessing headers() to explicitly signal that
the route requires runtime data and cannot be prerendered. This fixes build errors
when cacheComponents is enabled in next.config.ts.

The fix:
- Adds connection() call at the start of auth() function
- Gracefully handles older Next.js versions where connection() doesn't exist
- Properly re-throws prerendering bailout errors for Next.js to handle

Fixes prerendering errors like:
'During prerendering, headers() rejects when the prerender is complete'
@jacekradko jacekradko changed the title feat(nextjs): Allow PPR with auth() feat(nextjs): Fix error when using PPR with auth() Jan 6, 2026
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.

2 participants