Overview
Theauthkit function provides low-level access to authentication session data and headers. It’s designed for composable middleware/proxy patterns where you need to combine AuthKit with other middleware logic like rate limiting, custom redirects, or rewrites.
Use this with the handleAuthkitHeaders helper to properly merge AuthKit headers into your response.
Function signature
Parameters
The Next.js request object from your middleware/proxy function.
Configuration options
Custom redirect URI for OAuth callback. Overrides the environment variable.
Enable debug logging.
Screen hint for the authorization URL. Used when generating the
authorizationUrl in the response.Enable synchronous access token availability on initial page load.
Callback invoked when a session is successfully refreshed in the middleware.
Callback invoked when session refresh fails.
Return value
The authenticated session data, or an object with
user: null if not authenticated.When authenticated, includes:user: User object with profile informationaccessToken: JWT access tokensessionId: Session identifierorganizationId: Organization context (if applicable)role: User role (if applicable)roles: Array of user roles (if applicable)permissions: Array of permissions (if applicable)entitlements: Array of entitlements (if applicable)featureFlags: Array of enabled feature flags (if applicable)impersonator: Impersonator details (if user is being impersonated)
Headers to be forwarded to your application. Contains both internal AuthKit headers (for server components) and response headers (for the browser). Use
handleAuthkitHeaders or partitionAuthkitHeaders to properly handle these.The WorkOS authorization URL to redirect unauthenticated users to. Only present when the user is not authenticated.
Basic usage
Compose AuthKit with custom middleware logic:Usage with session refresh callbacks
Track session refresh events:Advanced usage with rewrites
For complex scenarios like rewrites, usepartitionAuthkitHeaders:
Important notes
- Always use
handleAuthkitHeadersorpartitionAuthkitHeaderswhen returning a response - Never pass
authorizationUrldirectly to a redirect without usinghandleAuthkitHeaders - The
authorizationUrlis a trusted value safe for redirects - For custom redirects, always validate user-controlled input before passing to
redirectoption - Session refresh callbacks are useful for logging but should not throw errors