;
}
```
### Evaluate feature flags
There are two ways to evaluate feature flags with AuthKit Next.js:
- Use the `feature_flags` access token claim when you want a simple session-scoped list of enabled flags for the signed-in user.
- Use the Feature Flags runtime client when you want server-side evaluation without storing every active flag in the user's session cookie.
#### Option 1: Use the `feature_flags` claim
For situations where you need access to the authenticated user's currently active feature flags and your environment includes the `feature_flags` access token claim, use `withAuth` to retrieve the flags from the WorkOS session.
```jsx
const { featureFlags } = await withAuth();
```
This is convenient for small flag sets because the flags are available with the user's session. Flag changes appear the next time the user logs in or the session is refreshed.
#### Option 2: Use the runtime client
> [!NOTE]
> The runtime client requires `WORKOS_API_KEY`. It isn't available in [public client mode](#public-client-keyless-mode).
Use the runtime client when your application has many feature flags, when the `feature_flags` claim makes the access token too large, or when you need server-side flag evaluation that stays in sync independently of the user's session. The runtime client keeps flag configuration in memory and syncs changes in the background, so create one shared instance per server process rather than one client per request.
```tsx
import { getFeatureFlagsRuntimeClient, withAuth } from '@workos-inc/authkit-nextjs';
const featureFlags = getFeatureFlagsRuntimeClient();
featureFlags.on('error', (error) => {
console.error('Feature flag sync failed:', error.message);
});
export default async function DashboardPage() {
const { user, organizationId } = await withAuth({ ensureSignedIn: true });
try {
await featureFlags.waitUntilReady({ timeoutMs: 5000 });
} catch (error) {
console.error('Feature flags client failed to initialize:', error);
}
const enabled = featureFlags.isEnabled('advanced-analytics', {
userId: user.id,
organizationId,
});
return enabled ? : ;
}
```
The `getFeatureFlagsRuntimeClient` helper returns the same runtime client for every call in the current server process. Options passed to `getFeatureFlagsRuntimeClient(options)` are only used when the client is created for the first time.
Register an `error` listener on the client so failed syncs reach your logs. With `@workos-inc/node` v9 through v11, a failed sync with no `error` listener stops all further syncs and can crash the process.
The runtime client evaluates flags with the `@workos-inc/node` version you install. Versions before v12 ignore targeting rules that serve `false`, so they can return `true` where the access token claim returns `false`. See the [Node runtime client guide](https://workos.com/docs/feature-flags/node-runtime-client).
### Requiring auth
For pages where a signed-in user is mandatory, you can use the `ensureSignedIn` option:
```jsx
// Server component
const { user } = await withAuth({ ensureSignedIn: true });
// Client component
const { user, loading } = useAuth({ ensureSignedIn: true });
```
Enabling `ensureSignedIn` will redirect users to AuthKit if they attempt to access the page without being authenticated. The Server Component guard first visits your existing `handleAuth()` callback route to set up PKCE; no additional route or configuration is needed. Rendering or prefetching the page does not set a verifier cookie. The cookie is created when the browser navigates to start authentication.
### Re-authentication
For sensitive actions you may want to require that the user authenticated _recently_, not just that they have a session. Use `checkRecentAuth` to read the access token's `auth_time` claim and decide whether to force a re-authentication.
`checkRecentAuth` returns data only and never redirects, so it's safe to call as the enforcement step inside a server action or server component. It **fails closed**: a session with no usable `auth_time` (or no signed-in user) is reported as `isStale: true`.
```ts
'use server';
import { checkRecentAuth, getSignInUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';
export async function deleteAccount() {
// Require that the user authenticated within the last 5 minutes
const { isStale } = await checkRecentAuth({ maxAge: 300 });
if (isStale) {
// Send the user through re-authentication. Passing `maxAge` forwards the OIDC
// `max_age` parameter, so AuthKit forces a fresh login when the most recent
// authentication is older than `maxAge` seconds.
redirect(await getSignInUrl({ maxAge: 300 }));
}
// ...perform the sensitive action
}
```
For client components, use the `useRecentAuth` hook to reflect recency in the UI. This is **presentation only** — always enforce recency on the server with `checkRecentAuth`.
```tsx
'use client';
import { useRecentAuth } from '@workos-inc/authkit-nextjs/components';
function SensitiveActionButton() {
const { loading, isStale } = useRecentAuth({ maxAge: 300 });
if (loading) {
return ;
}
return ;
}
```
### Refreshing the session
Use the `refreshSession` method in a server action or route handler to fetch the latest session details, including any changes to the user's roles or permissions.
The `organizationId` parameter can be passed to `refreshSession` in order to switch the session to a different organization. If the current session is not authorized for the next organization, an appropriate [authentication error](https://workos.com/docs/reference/user-management/authentication-errors) will be returned.
In client components, you can refresh the session with the `refreshAuth` hook.
```tsx
'use client';
import { useAuth } from '@workos-inc/authkit-nextjs/components';
import React, { useEffect } from 'react';
export function SwitchOrganizationButton() {
const { user, organizationId, loading, refreshAuth } = useAuth();
useEffect(() => {
// This will log out the new organizationId after refreshing the session
console.log('organizationId', organizationId);
}, [organizationId]);
if (loading) {
return
Loading...
;
}
const handleRefreshSession = async () => {
const result = await refreshAuth({
// Provide the organizationId to switch to
organizationId: 'org_123',
});
if (result?.error) {
console.log('Error refreshing session:', result.error);
}
};
if (user) {
return ;
} else {
return
Not signed in
;
}
}
```
### Access Token Management
#### useAccessToken Hook
This library provides a `useAccessToken` hook for client-side access token management with automatic refresh functionality.
##### Features
- Automatic token refresh before expiration
- Manual refresh capability
- Loading and error states
- Synchronized with the main authentication session
- Race condition prevention
##### When to Use
Use this hook when you need direct access to the JWT token for:
- Making authenticated API calls
- Setting up external auth-dependent libraries
- Implementing custom authentication logic
##### Basic Usage
```jsx
function ApiClient() {
const { accessToken, loading, error, refresh } = useAccessToken();
if (loading) return
);
}
```
##### API Reference
| Property | Type | Description |
| ------------- | ------------------------------------ | --------------------------------------------- |
| `accessToken` | `string \| undefined` | The current access token |
| `loading` | `boolean` | True when token is being fetched or refreshed |
| `error` | `Error \| null` | Error during token fetch/refresh, or null |
| `refresh` | `() => Promise` | Manually refresh the token |
##### Integration with useAuth
The `useAccessToken` hook automatically synchronizes with the main authentication session. When you call `refreshAuth()` from `useAuth`, the access token will update accordingly. Similarly, using the `refresh()` method from `useAccessToken` will update the entire authentication session.
##### Security Considerations
JWT tokens are sensitive credentials and should be handled carefully:
- Only use the token where necessary
- Don't store tokens in localStorage or sessionStorage
- Be cautious about exposing tokens in your application state
### Passing Custom State Through Authentication
You can pass custom state data through the authentication flow using the `state` parameter. The state parameter is a string value that gets passed through OAuth and returned in the callback. Generate the URL in a Route Handler or Server Action, serializing complex data as JSON:
```ts
// app/sign-in/route.ts
import { getSignInUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';
export async function GET() {
const signInUrl = await getSignInUrl({
state: JSON.stringify({
teamId: 'team_123',
feature: 'billing',
referrer: 'pricing-page',
timestamp: Date.now(),
}),
});
redirect(signInUrl);
}
```
The state data is available in the callback handler:
```ts
// app/callback/route.ts
import { handleAuth } from '@workos-inc/authkit-nextjs';
export const GET = handleAuth({
onSuccess: async ({ user, state }) => {
// Parse the state string back to an object
const customData = state ? JSON.parse(state) : null;
// Access your custom state data
if (customData?.teamId) {
await addUserToTeam(user.id, customData.teamId);
}
if (customData?.feature) {
await trackFeatureActivation(user.id, customData.feature);
}
// Track where the user came from
await analytics.track('sign_in_completed', {
userId: user.id,
referrer: customData?.referrer,
timestamp: customData?.timestamp,
});
},
});
```
> **Note**: The `state` parameter is an opaque string as defined by OAuth 2.0 (RFC 6749). If you need to pass structured data, you must serialize it yourself using `JSON.stringify()` and parse it with `JSON.parse()` in the callback.
This is useful for:
- Tracking user journey and referral sources
- Maintaining context about what the user was trying to do before authentication
- Implementing custom onboarding flows
- Analytics and attribution tracking
### Session Refresh Callbacks
When using the `authkit` function directly, you can provide callbacks to be notified when a session is refreshed:
```typescript
const { session, headers } = await authkit(request, {
onSessionRefreshSuccess: async ({ accessToken, user, impersonator }) => {
// Log successful refresh
console.log(`Session refreshed for ${user.email}.`);
},
onSessionRefreshError: async ({ error, request }) => {
// Log refresh failure
console.error('Session refresh failed:', error);
// Notify monitoring system
await notifyMonitoring('session_refresh_failed', {
url: request.url,
error: error.message,
});
},
});
```
These callbacks provide a way to perform side effects when sessions are refreshed in the proxy/middleware. Common use cases include:
- Logging authentication events
- Updating last activity timestamps
- Triggering organization-specific data prefetching
- Recording failed refresh attempts
### Proxy / Middleware auth
The default behavior of this library is to request authentication via the `withAuth` method on a per-page basis. There are some use cases where you don't want to call `withAuth` (e.g. you don't need user data for your page) or if you'd prefer a "secure by default" approach where every route defined in your proxy/middleware matcher is protected unless specified otherwise. In those cases you can opt-in to use `middlewareAuth` instead:
```ts
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';
export default authkitMiddleware({
middlewareAuth: {
enabled: true,
unauthenticatedPaths: ['/', '/about'],
},
});
// Match against pages that require auth
// Leave this out if you want auth on every resource (including images, css etc.)
export const config = { matcher: ['/', '/admin/:path*', '/about'] };
```
In the above example the `/admin` page will require a user to be signed in, whereas `/` and `/about` can be accessed without signing in.
`unauthenticatedPaths` uses the same glob logic as the [Next.js matcher](https://nextjs.org/docs/pages/building-your-application/routing/middleware#matcher).
### Eager auth
The `eagerAuth` option enables synchronous access to authentication tokens on initial page load, which is required by some third-party services that validate tokens directly with WorkOS. When enabled, tokens are available immediately without requiring an asynchronous fetch.
#### How it works
When `eagerAuth: true` is set, the proxy/middleware temporarily stores the access token in a short-lived cookie (30 seconds) that is:
- Only set on initial page loads (not API or prefetch requests)
- Immediately consumed and deleted by the client
- Available synchronously on the first render
#### Usage
Enable eager auth in your proxy/middleware configuration:
```ts
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';
export default authkitMiddleware({
eagerAuth: true,
});
```
Then access the token synchronously in your client components:
```tsx
'use client';
import { useAccessToken } from '@workos-inc/authkit-nextjs/components';
function MyComponent() {
const { getAccessToken } = useAccessToken();
async function handleClick() {
// Token is available immediately on initial page load
const token = await getAccessToken();
// Use with third-party services that need immediate token access
if (token) {
// Initialize your third-party client with the token
thirdPartyClient.authenticate(token);
}
}
return ;
}
```
#### Security considerations
Eager auth makes tokens briefly accessible via JavaScript (30-second window) to enable synchronous access. This is a common pattern used by many authentication libraries and is generally safe with standard XSS protections.
**Best practices:**
- Implement a Content Security Policy (CSP) if handling sensitive data
- Review third-party scripts on authenticated pages
- Use the standard `getAccessToken()` method when synchronous access isn't required
**When to use:**
- Third-party services that require synchronous token access
- Real-time features that need immediate authentication
- When you want to avoid loading states on initial render
**When to use standard async tokens:**
- Most API calls where a brief loading state is acceptable
- When you don't need immediate token access on page load
### Proactive session refresh
The proxy/middleware proactively refreshes the session when the access token is within a buffer of its expiry, mirroring the buffer the client token store already uses: 60 seconds, or 30 seconds for tokens with a total lifetime of 5 minutes or less. This ensures a token handed to `withAuth()` and then to a server-side consumer (a Server Component fetch, an API call to a service that validates the token) cannot expire mid-request due to render latency, network round trips, or clock skew.
Use the `refreshBufferSeconds` option to tune the buffer, or set it to `0` to disable proactive refresh and only refresh once the token has expired:
```ts
export default authkitProxy({
refreshBufferSeconds: 120,
});
```
If a proactive refresh fails (for example, a concurrent request already rotated the single-use refresh token), the request is served with the current access token, provided it is still valid at that point; the session is never destroyed while the access token remains valid. If the token expired during the failed refresh attempt, the session is cleared and the request is redirected to sign in, as with any expired session.
Note that when several requests land inside the buffer window at the same time, only one wins the refresh; each of the others may pay a failed-refresh round trip to WorkOS before being served with the current token. This costs some added latency on those requests during the buffer window, but no user-visible failure.
### Signing out
Use the `signOut` method to sign out the current logged in user and redirect to your app's default Sign-out URI. Sign-out URIs are set in your WorkOS dashboard under your application's "Redirects" tab.
To use a non-default Sign-out URI, you can use the `returnTo` parameter.
```tsx
await signOut({ returnTo: 'https://your-app.com/signed-out' });
```
### Visualizing an impersonation
Render the `Impersonation` component in your app so that it is clear when someone is [impersonating a user](https://workos.com/docs/user-management/impersonation).
The component will display a frame with some information about the impersonated user, as well as a button to stop impersonating.
> [!IMPORTANT]
> Impersonation requires a configured **Initiate login URI** in your WorkOS dashboard. See the [Initiate login URI](#initiate-login-uri) setup instructions. Without it, impersonation from the WorkOS dashboard will fail with a `Missing required auth parameter` error.
```jsx
import { Impersonation, AuthKitProvider } from '@workos-inc/authkit-nextjs/components';
export default function App() {
return (
{/* Your app content */}
);
}
```
### Get the access token
Sometimes it is useful to obtain the access token directly, for instance to make API requests to another service.
```jsx
import { withAuth } from '@workos-inc/authkit-nextjs';
export default async function HomePage() {
const { accessToken } = await withAuth();
if (!accessToken) {
return
;
}
```
### Sign up paths
The `signUpPaths` option can be passed to `authkitMiddleware` to specify paths that should use the 'sign-up' screen hint when redirecting to AuthKit. This is useful for cases where you want a path that mandates authentication to be treated as a sign up page.
```ts
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';
export default authkitMiddleware({
signUpPaths: ['/account/sign-up', '/dashboard/:path*'],
});
```
### Validate an API key
Use the `validateApiKey` function in your application's public API endpoints to parse a [Bearer Authentication](https://swagger.io/docs/specification/v3_0/authentication/bearer-authentication/) header and validate the [API key](https://workos.com/docs/authkit/api-keys) with WorkOS. It requires `WORKOS_API_KEY` and isn't available in [public client mode](#public-client-keyless-mode).
```ts
import { NextResponse } from 'next/server';
import { validateApiKey } from '@workos-inc/authkit-nextjs';
export async function GET() {
const { apiKey } = await validateApiKey();
if (!apiKey) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.json({ success: true });
}
```
### Advanced: Direct access to the WorkOS client
For advanced use cases or functionality not covered by the helper methods, you can access the underlying WorkOS client directly. WorkOS management APIs need an API key; in [public client mode](#public-client-keyless-mode) they throw an `ApiKeyRequiredException`.
```typescript
import { getWorkOS } from '@workos-inc/authkit-nextjs';
// Get the configured WorkOS client instance
const workos = getWorkOS();
// Use any WorkOS SDK method
const organizations = await workos.organizations.listOrganizations({
limit: 10,
});
```
### Advanced: Custom authentication flows
While the standard authentication flow handles session management automatically, some use cases require manually creating and storing a session. This is useful for custom authentication flows like email verification or token exchange.
For these scenarios, you can use the `saveSession` function:
```typescript
import { saveSession } from '@workos-inc/authkit-nextjs';
import { getWorkOS } from '@workos-inc/authkit-nextjs';
// Example: Email verification flow
async function handleEmailVerification(req) {
const { code } = await req.json();
// Authenticate with the WorkOS API directly
const authResponse = await getWorkOS().userManagement.authenticateWithEmailVerification({
clientId: process.env.WORKOS_CLIENT_ID,
code,
});
// Save the session data to a cookie
await saveSession(
{
accessToken: authResponse.accessToken,
refreshToken: authResponse.refreshToken,
user: authResponse.user,
impersonator: authResponse.impersonator,
},
req,
);
return Response.redirect('/dashboard');
}
```
> [!NOTE]
> This is an advanced API intended for specific integration scenarios, such as those users using self-hosted AuthKit. If you're using hosted AuthKit you should not need this.
The `saveSession` function accepts either a `NextRequest` object or a URL string as its second parameter.
```typescript
// With NextRequest
await saveSession(session, req);
// With URL string
await saveSession(session, 'https://example.com/callback');
```
### CDN Deployments and Caching
AuthKit automatically implements cache security measures to protect against session leakage in CDN environments. This is particularly important when deploying to AWS with SST/OpenNext, Cloudflare, or other CDN configurations.
#### How It Works
The library automatically sets appropriate cache headers on all authenticated requests:
- `Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0` - Aggressive cache prevention with multiple directives
- `Pragma: no-cache` - HTTP/1.0 compatibility
- `Expires: 0` - HTTP/1.0 cache expiration
- `Vary: Cookie` - Ensures CDNs differentiate between different users (defense-in-depth)
- `x-middleware-cache: no-cache` - Prevents Next.js proxy/middleware result caching
These headers are applied automatically when:
- A session cookie is present in the request
- An Authorization header is detected
- An active authenticated session exists
#### Performance Considerations
**Authenticated pages:** Will not be cached at the CDN level and will always hit your origin server. This is the correct and secure behavior for session-based authentication.
**Public pages:** Unaffected by these security measures. Public routes without authentication context can still be cached normally.
### Debugging
To enable debug logs, initialize the proxy/middleware with the debug flag enabled.
```js
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';
export default authkitMiddleware({ debug: true });
```
### Security
#### PKCE and CSRF protection
This library uses [PKCE](https://datatracker.ietf.org/doc/html/rfc7636) (Proof Key for Code Exchange) and a sealed (encrypted) OAuth state parameter on every authorization request. The state contains a cryptographic nonce for CSRF protection per [RFC 9700](https://datatracker.ietf.org/doc/rfc9700/) and a code verifier for protection against authorization code interception. During sign-in, a short-lived `wos-auth-verifier` cookie is set containing the sealed state. This cookie is automatically cleaned up after the callback completes.
> [!NOTE]
> **Upgrading to v3:** PKCE is now always enabled. The `WORKOS_ENABLE_PKCE` environment variable is no longer needed and can be removed from your configuration.
#### Cookie requirements
The `wos-auth-verifier` cookie must survive the round-trip from sign-in initiation to the callback. On callback, the library verifies that the cookie is present and matches the URL `state` parameter — this two-channel check is what prevents CSRF attacks.
If the cookie is missing or doesn't match, authentication will fail with one of:
- `Sign-in session could not be verified` — the cookie was not sent back with the callback request. This typically happens when the session has expired or a reverse proxy or CDN strips `Set-Cookie` headers on redirects.
- `OAuth state mismatch` — the cookie and URL `state` parameter don't match, indicating a possible CSRF attack or cookie corruption.
> [!IMPORTANT]
> **Upgrading to v3:** Previous versions would silently fall back to verifying only the URL `state` parameter when the cookie was missing. This fallback has been removed because it disabled CSRF protection. If you see `Sign-in session could not be verified` errors after upgrading, ensure that `Set-Cookie` headers are propagated on redirects between your application and the user's browser.
### Troubleshooting
#### `Missing required auth parameter` when impersonating from the WorkOS dashboard
This error occurs when WorkOS-initiated flows (like dashboard impersonation) redirect directly to your callback URL without going through your application's sign-in flow. Because this library enforces PKCE/CSRF verification on every callback, the request is rejected when the required `state` parameter is missing.
**Fix:** Configure an [Initiate login URI](#initiate-login-uri) in your WorkOS dashboard so that impersonation flows route through your app first, allowing PKCE/state to be set up before redirecting to WorkOS.
#### NEXT_REDIRECT error when using try/catch blocks
Wrapping a `withAuth({ ensureSignedIn: true })` call in a try/catch block will cause a `NEXT_REDIRECT` error. This is because `withAuth` will attempt to redirect the user to AuthKit if no session is detected and redirects in Next must be [called outside a try/catch](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#redirecting).
#### Module build failed: UnhandledSchemeError: Reading from "node:crypto" is not handled by plugins (Unhandled scheme)
You may encounter this error if you attempt to import server side code from authkit-nextjs into a client component. Likely you are using `withAuth` in a client component instead of the `useAuth` hook. Either move the code to a server component or use the `useAuth` hook.