Overview
TheauthkitMiddleware function creates a Next.js middleware (or proxy in Next.js 16+) that automatically manages authentication for your application routes. It handles session management, cookie refresh, and redirects unauthenticated users to AuthKit when needed.
Function signature
Parameters
Configuration options for the middleware
Custom redirect URI for OAuth callback. Useful for dynamic environments like Vercel preview deployments. Overrides the
WORKOS_REDIRECT_URI environment variable.Configure middleware-level authentication enforcement
Enable middleware-level authentication. When true, all routes in the matcher require authentication unless listed in
unauthenticatedPaths.Array of path patterns that don’t require authentication. Supports glob patterns like
/about or /blog/:path*.Enable debug logging for troubleshooting authentication issues.
Array of path patterns that should use the sign-up screen hint when redirecting to AuthKit. Supports glob patterns.
Enable synchronous access token availability on initial page load. Required by some third-party services. When enabled, temporarily stores the access token in a 30-second cookie for immediate client-side access.
Return value
A Next.js middleware function that can be exported as the default export from your
middleware.ts (Next.js ≤15) or proxy.ts (Next.js 16+) file.Basic usage
Usage with middleware auth
Protect all routes except specific public pages:Usage with custom redirect URI
Dynamically set the redirect URI for preview deployments:Usage with sign-up paths
Direct users to the sign-up screen for specific routes:Usage with eager auth
Enable synchronous token access for third-party services:Important notes
- The middleware must be in the root of your project (not in
srcorappdirectories) - Use a
config.matcherto specify which routes should be processed - Avoid catch-all matchers like
['/:path*']that can intercept static assets and break styling - For broad protection, use:
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] - In Next.js 16+, the file should be named
proxy.tsinstead ofmiddleware.ts