Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Jan 14, 2026

Summary

Adds baseline support for Next.js 16 cache components (cacheComponents) by improving error detection and providing helpful error messages.

  • Add isNextjsUseCacheError() helper to detect "use cache" context errors
  • Update isPrerenderingBailout() to detect cache component prerendering errors
  • Update buildRequestLike() to provide helpful error message when auth() is called inside a "use cache" function
  • Update clerkClient() to re-throw "use cache" errors
  • Add unit tests for error detection helpers

Problem

When Next.js 16 cache components are enabled and a developer calls auth() or currentUser() inside a "use cache" function, they receive a cryptic error about headers() rejecting during prerendering.

Solution

Detect these errors and provide a helpful message with a code example showing the correct pattern:

Clerk: auth() and currentUser() cannot be called inside a "use cache" function.
These functions access `headers()` internally, which is a dynamic API not allowed in cached contexts.

To fix this, call auth() outside the cached function and pass the userId as an argument:

  async function getCachedUser(userId: string) {
    "use cache";
    const client = await clerkClient();
    return client.users.getUser(userId);
  }

  // In your component/page:
  const { userId } = await auth();
  if (userId) {
    const user = await getCachedUser(userId);
  }

Test plan

  • Unit tests added for isPrerenderingBailout() and isNextjsUseCacheError()
  • All 26 tests pass
  • Build succeeds
  • Manual testing with Next.js 16 test app (follow-up)

How to verify

Setup

  1. Create or use a Next.js 16 app with cacheComponents enabled in next.config.ts:

    const nextConfig: NextConfig = {
      experimental: {
        cacheComponents: true,
      },
    };
  2. Install the PR preview package:

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

Test the error detection

Create a page that calls auth() inside a "use cache" function:

// app/test-cache/page.tsx
import { auth } from '@clerk/nextjs/server';

async function getCachedData() {
  "use cache";
  const { userId } = await auth(); // ❌ This should trigger our helpful error
  return { userId };
}

export default async function TestPage() {
  const data = await getCachedData();
  return <div>{JSON.stringify(data)}</div>;
}

Expected behavior

Before this PR: Cryptic error about headers() rejecting during prerendering

After this PR: Clear error message explaining the issue and showing the correct pattern:

Clerk: auth() and currentUser() cannot be called inside a "use cache" function.
These functions access `headers()` internally, which is a dynamic API not allowed in cached contexts.

To fix this, call auth() outside the cached function and pass the userId as an argument:
...

Related

Summary by CodeRabbit

  • New Features

    • Added support for Next.js 16 cache components with improved error detection and handling capabilities.
  • Improvements

    • Clearer error messages when authentication functions are used incorrectly inside a "use cache" function.
    • Enhanced error handling across server utilities for cache boundary detection and prerendering scenarios.

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

- Add `isNextjsUseCacheError()` helper to detect "use cache" context errors
- Update `isPrerenderingBailout()` to detect cache component prerendering errors
- Update `buildRequestLike()` to provide helpful error message with code example
  when auth() is called inside a "use cache" function
- Update `clerkClient()` to re-throw "use cache" errors
- Add unit tests for error detection helpers
@changeset-bot
Copy link

changeset-bot bot commented Jan 14, 2026

🦋 Changeset detected

Latest commit: 376fd84

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 Jan 14, 2026

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 15, 2026 5:45pm

Review with Vercel Agent

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 14, 2026

📝 Walkthrough

Walkthrough

Adds detection and handling for Next.js 16 "use cache" component errors across the Clerk Next.js package. Introduces precompiled regexes, an exported helper isNextjsUseCacheError, and USE_CACHE_ERROR_MESSAGE. Integrates detection into buildRequestLike, clerkClient, auth, and currentUser to rethrow matched errors with a standardized message. Adds tests for isPrerenderingBailout and isNextjsUseCacheError, and a changeset documenting the capability.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title clearly and accurately summarizes the main change: adding support for Next.js 16 cache components with improved error detection and clearer error messages.

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



📜 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 16cb41b and 376fd84.

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

3-9: LGTM!

Regex patterns are properly hoisted as module-level constants for performance. The patterns appropriately cover the various error message formats across Next.js versions.


31-50: LGTM!

Well-documented type guard with appropriate dual-condition logic to minimize false positives. The compound pattern check requiring both "dynamic data source" AND "cache" is a sensible approach.


52-70: LGTM!

Excellent error message following coding guidelines - provides meaningful context, explains the root cause, and includes actionable recovery suggestions with a working code example.


86-89: LGTM!

Error handling follows the established pattern in this function. The cache error check is correctly ordered after the prerendering bailout check, ensuring proper error propagation.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Jan 14, 2026

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

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

@clerk/upgrade

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

@clerk/vue

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

commit: 376fd84

Wrap auth() and currentUser() in try-catch to catch "use cache" errors
that bubble up from the Next.js cache boundary. The original
implementation only caught errors inside buildRequestLike(), but Next.js
throws these errors at a higher level.
// note: new error message syntax introduced in [email protected]
// but we still want to support older versions.
// https://github.com/vercel/next.js/pull/61332 (dynamic-rendering.ts:153)
const routeRegex = /Route .*? needs to bail out of prerendering at this point because it used .*?./;
Copy link
Member

Choose a reason for hiding this comment

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

nit: consider hoisting this pattern out of the function like the others in this file

Copy link
Member Author

Choose a reason for hiding this comment

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

Addressed

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.

3 participants