-
Notifications
You must be signed in to change notification settings - Fork 382
feat(nextjs): Support static export #6679
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds 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
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)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this 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 importWith 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 APIMove/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 subpathHelps 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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 existThe
./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 componentUsing
'use client'
avoids the static export server-action build error.
12-18
: Props shape looks right for static contextsDeriving from
ClerkProviderProps
and makingpublishableKey
optional aligns with env-driven configuration.
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>; | ||
}; |
There was a problem hiding this comment.
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.
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.
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.Type of change
Summary by CodeRabbit
New Features
Chores