Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Sep 1, 2025

Description

This PR introduces a new <ClerkProvider /> (for App Router) exported from @clerk/nextjs/static that allows statically exported Next application to function as expected.

Issue

Previously a developer would receive an error during next build that "Server Actions are not supported with static export". This is because the current ClerkProviders for app router use many of the unsupported features that are missing when an application is statically exported.

Solution

Expose a minimal <ClerkProvider/> as a client component that provides clerk.js with the correct routing functions and the convenient environment variable resolution.

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

  • New Features

    • Introduced a static-export–friendly ClerkProvider for Next.js, designed for client-side use only.
    • Supports optional override of the publishable key via a prop.
    • Integrates client-side navigation helpers for push/replace behavior.
    • Suitable for static builds without SSR or route revalidation.
  • Chores

    • Added a new public export for the static provider.
    • Updated the package’s published files to include the static build artifacts, enabling direct import in consuming apps.

Copy link

changeset-bot bot commented Sep 1, 2025

⚠️ No Changeset found

Latest commit: 643b28a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@panteliselef panteliselef self-assigned this Sep 1, 2025
Copy link

vercel bot commented Sep 1, 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 Sep 2, 2025 11:39am

Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

Walkthrough

Adds a static-export-specific ClerkProvider wrapper and exposes it via a new "./static" subpath export in the Next.js package. Updates package.json exports and files list to publish the new static build artifacts.

Changes

Cohort / File(s) Summary
Package exports and publish config
packages/nextjs/package.json
Adds ./static subpath in exports with types, import, and require targets. Updates files array to include static artifacts.
Static Clerk provider (client)
packages/nextjs/src/static.tsx
Introduces a static-export-friendly ClerkProvider wrapper. Uses useAwaitablePush/Replace, merges props with env via mergeNextClerkPropsWithEnv, and renders @clerk/clerk-react’s provider. Intended for static export (client-only).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as App (Client)
  participant SCP as StaticClerkProvider
  participant Hooks as useAwaitablePush/Replace
  participant Merge as mergeNextClerkPropsWithEnv
  participant RCP as ReactClerkProvider (@clerk/clerk-react)
  participant Env as NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY

  App->>SCP: Render with props (optional publishableKey)
  SCP->>Hooks: Obtain routerPush/routerReplace (awaitable)
  SCP->>Env: Read publishableKey (if not provided)
  SCP->>Merge: Merge props + env + router handlers
  Merge-->>SCP: Merged provider props
  SCP->>RCP: Render with merged props
  RCP-->>App: Children rendered in Clerk context

  note over SCP,Merge: Static-export context (no SSR/route revalidation)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through routes with gentle grace,
A static breeze, no server chase;
With keys in paw and props aligned,
I merge the env, then press “Replace” in kind.
In silent grass, my context grows—
Push, hop, render—on it goes. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/static-export

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@panteliselef panteliselef requested a review from a team September 1, 2025 16:07
Copy link

pkg-pr-new bot commented Sep 1, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 643b28a

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: 1

🧹 Nitpick comments (5)
packages/nextjs/package.json (1)

69-71: Confirm necessity of adding "static" to files[]

If no top-level "static" directory is published (only dist/* artifacts), this entry is unnecessary. Either remove it or ensure the directory exists at publish time to avoid confusion.

packages/nextjs/src/static.tsx (4)

3-6: Drop unused default React import

With the automatic JSX runtime, the default React import isn’t needed here.

-import React from 'react';

20-23: Promote these comments to JSDoc above the exported API

Move/merge these notes into the JSDoc for the exported ClerkProvider to ensure they appear in type hints and generated docs.


24-29: Tighten and expand public JSDoc (grammar + guidance)

Minor grammar fix and add a short usage note to meet the “public API JSDoc” guideline.

 /**
- * The ClerkProvider exported from `/static` should only be used for static exports only.
- * Using this provider means that you opt out of authorization checks on the server.
+ * The ClerkProvider exported from `/static` must be used only for static exports.
+ * Using this provider opts you out of server-side authorization checks (no RSC/middleware).
+ * Example:
+ *   import { ClerkProvider } from '@clerk/nextjs/static';
+ *   // ... wrap your app root on the client
  * @param props
  * @returns
  */

43-43: Also export the props type from this subpath

Helps consumers type their wrappers without importing from internal paths.

-export { StaticClerkProvider as ClerkProvider };
+export { StaticClerkProvider as ClerkProvider };
+export type { NextStaticClerkProviderProps as StaticClerkProviderProps };
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 a50cfc8 and 0017488.

📒 Files selected for processing (2)
  • packages/nextjs/package.json (1 hunks)
  • packages/nextjs/src/static.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/package.json
  • packages/nextjs/src/static.tsx
packages/*/package.json

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

All publishable packages should be placed under the packages/ directory

packages/*/package.json: All publishable packages must be located in the 'packages/' directory.
All packages must be published under the @clerk namespace on npm.
Semantic versioning must be used across all packages.

Files:

  • packages/nextjs/package.json
**/*.{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/static.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/nextjs/src/static.tsx
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/nextjs/src/static.tsx
**/*.{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/nextjs/src/static.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/nextjs/src/static.tsx
**/*.{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/static.tsx
**/*.tsx

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

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/nextjs/src/static.tsx
🧬 Code graph analysis (1)
packages/nextjs/src/static.tsx (2)
packages/types/src/utils.ts (1)
  • Without (105-107)
packages/nextjs/src/utils/mergeNextClerkPropsWithEnv.ts (1)
  • mergeNextClerkPropsWithEnv (7-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). (26)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
packages/nextjs/package.json (1)

57-62: New subpath export looks correct; double-check build outputs exist

The ./static subpath mapping is consistent with existing patterns. Please verify the build actually emits:

  • dist/esm/static.js
  • dist/cjs/static.js
  • dist/types/static.d.ts
packages/nextjs/src/static.tsx (2)

1-1: Good call making this a client component

Using 'use client' avoids the static export server-action build error.


12-18: Props shape looks right for static contexts

Deriving from ClerkProviderProps and making publishableKey optional aligns with env-driven configuration.

Comment on lines +30 to +41
const StaticClerkProvider = (props: NextStaticClerkProviderProps) => {
const push = useAwaitablePush();
const replace = useAwaitableReplace();
const mergedProps = mergeNextClerkPropsWithEnv({
...props,
// @ts-expect-error Error because of the stricter types of internal `push`
routerPush: push,
// @ts-expect-error Error because of the stricter types of internal `replace`
routerReplace: replace,
});
return <ReactClerkProvider {...mergedProps}>{props.children}</ReactClerkProvider>;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove ts-expect-error by adapting router functions; add explicit return type and a dev-time guard

Avoid suppressing type errors and add an explicit return type for this public component. Also surface a clear dev warning when publishableKey is missing.

-const StaticClerkProvider = (props: NextStaticClerkProviderProps) => {
-  const push = useAwaitablePush();
-  const replace = useAwaitableReplace();
-  const mergedProps = mergeNextClerkPropsWithEnv({
-    ...props,
-    // @ts-expect-error Error because of the stricter types of internal `push`
-    routerPush: push,
-    // @ts-expect-error Error because of the stricter types of internal `replace`
-    routerReplace: replace,
-  });
-  return <ReactClerkProvider {...mergedProps}>{props.children}</ReactClerkProvider>;
-};
+const StaticClerkProvider = (props: NextStaticClerkProviderProps): React.JSX.Element => {
+  const push = useAwaitablePush();
+  const replace = useAwaitableReplace();
+  // Adapt to the looser router function shape expected by the provider (fire-and-forget).
+  const routerPush = (to: string) => { void push(to); };
+  const routerReplace = (to: string) => { void replace(to); };
+
+  const mergedProps = mergeNextClerkPropsWithEnv({
+    ...props,
+    routerPush,
+    routerReplace,
+  });
+
+  if (!mergedProps.publishableKey && process.env.NODE_ENV !== 'production') {
+    // Visible, actionable feedback in dev builds.
+    // eslint-disable-next-line no-console
+    console.error(
+      'Clerk: Missing publishableKey. Set NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY or pass publishableKey to <ClerkProvider /> from @clerk/nextjs/static.'
+    );
+  }
+
+  return <ReactClerkProvider {...mergedProps}>{props.children}</ReactClerkProvider>;
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const StaticClerkProvider = (props: NextStaticClerkProviderProps) => {
const push = useAwaitablePush();
const replace = useAwaitableReplace();
const mergedProps = mergeNextClerkPropsWithEnv({
...props,
// @ts-expect-error Error because of the stricter types of internal `push`
routerPush: push,
// @ts-expect-error Error because of the stricter types of internal `replace`
routerReplace: replace,
});
return <ReactClerkProvider {...mergedProps}>{props.children}</ReactClerkProvider>;
};
const StaticClerkProvider = (props: NextStaticClerkProviderProps): React.JSX.Element => {
const push = useAwaitablePush();
const replace = useAwaitableReplace();
// Adapt to the looser router function shape expected by the provider (fire-and-forget).
const routerPush = (to: string) => { void push(to); };
const routerReplace = (to: string) => { void replace(to); };
const mergedProps = mergeNextClerkPropsWithEnv({
...props,
routerPush,
routerReplace,
});
if (!mergedProps.publishableKey && process.env.NODE_ENV !== 'production') {
// Visible, actionable feedback in dev builds.
// eslint-disable-next-line no-console
console.error(
'Clerk: Missing publishableKey. Set NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY or pass publishableKey to <ClerkProvider /> from @clerk/nextjs/static.'
);
}
return <ReactClerkProvider {...mergedProps}>{props.children}</ReactClerkProvider>;
};
🤖 Prompt for AI Agents
packages/nextjs/src/static.tsx lines 30-41: The component currently suppresses
type errors with ts-expect-error, lacks an explicit return type, and doesn’t
warn when publishableKey is missing; fix by giving StaticClerkProvider an
explicit React.FC<NextStaticClerkProviderProps> (or appropriate ReactElement)
return type, adapt useAwaitablePush/useAwaitableReplace wrappers so their
signatures match the expected routerPush/routerReplace types (e.g., accept same
args and return Promise<boolean> or void as required) and remove the
ts-expect-error comments, and add a dev-only guard (process.env.NODE_ENV !==
'production') that logs a clear console.warn if mergedProps.publishableKey is
falsy before rendering. Ensure changes preserve behavior and types without using
any ts-expect-error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants