Overview
ThehandleAuthkitHeaders function creates a NextResponse with properly merged AuthKit headers. It ensures that:
- Internal AuthKit headers are forwarded to your pages (so
withAuth()works) - Session data is never leaked to the browser
- Only safe response headers are sent to the client
- Cache headers are properly set when cookies are present
- Redirects are properly normalized to absolute URLs
authkit function for composable middleware.
Function signature
Parameters
The Next.js request object from your middleware/proxy function.
The headers object returned from the
authkit() function. Contains both internal AuthKit headers and response headers.Optional configuration for the response
URL to redirect to. Can be relative (e.g.,
/login) or absolute (e.g., https://example.com/login). Relative URLs are automatically normalized to absolute URLs based on the request URL.HTTP redirect status code. Defaults to 307 for GET/HEAD requests, and 303 for POST/PUT/DELETE requests (to prevent form resubmission).
Return value
A Next.js response object with properly merged headers. Either a redirect response (if
redirect option provided) or a continuation response that forwards the request to the next handler.Basic usage
Continue the request with merged headers:Usage with redirects
Redirect unauthenticated users to sign-in:Usage with relative redirects
Redirect to a relative path:Usage with custom redirect status
Control the redirect behavior:What headers are forwarded?
Internal request headers (forwarded to pages, never sent to browser)
x-workos-middleware: Flag indicating AuthKit middleware is activex-workos-session: Encrypted session datax-url: Current request URLx-redirect-uri: OAuth callback URIx-sign-up-paths: Paths configured for sign-up flow
Response headers (sent to browser)
set-cookie: Session cookies (multiple cookies properly appended)cache-control: Auto-set tono-storewhen cookies are presentvary: Cache variation keys (deduplicated when merging)www-authenticate: Authentication challengesproxy-authenticate: Proxy authentication challengeslink: Pagination, preload hints, etc.x-middleware-cache: Set tono-cacheto prevent stale responses
Important notes
- Always use this helper when working with
authkit()function - Never manually forward AuthKit headers to the browser
- Client-injected
x-workos-*headers are automatically stripped and replaced with trusted values - Only use the
redirectoption with trusted values (likeauthorizationUrlfromauthkit()) - Never pass user-controlled input directly to
redirectwithout validation - Relative redirect URLs are automatically converted to absolute URLs
- POST/PUT/DELETE requests default to 303 status to prevent form resubmission