Overview
ThepartitionAuthkitHeaders function separates AuthKit headers into two groups:
- Request headers: Internal AuthKit headers to be forwarded to your pages (for
withAuth()to work) - Response headers: Safe headers to be sent to the browser (cookies, cache control, etc.)
handleAuthkitHeaders instead.
Function signature
Parameters
The Next.js request object from your middleware/proxy function.
The headers object returned from the
authkit() function.Return value
Headers to be forwarded to downstream handlers and pages. Includes:
- All original request headers
- Internal AuthKit headers (
x-workos-middleware,x-workos-session,x-url, etc.) - Client-injected AuthKit headers are stripped and replaced with trusted values
Headers safe to send to the browser. Includes:
set-cookie: Session cookiescache-control: Set tono-storewhen cookies are presentvary: Cache variation keyswww-authenticate: Authentication challengesproxy-authenticate: Proxy authenticationlink: Pagination, preload hints, etc.x-middleware-cache: Set tono-cache
Basic usage with rewrites
Use withapplyResponseHeaders for custom response creation:
Usage with custom response logic
Manually construct responses for complex scenarios:Usage with dynamic rewrites
Rewrite based on authentication state:Security considerations
This function automatically:- Strips client-injected headers: Any
x-workos-*headers from the client are removed and replaced with trusted values from AuthKit - Filters response headers: Only allowlisted headers are included in
responseHeaders - Auto-sets cache headers:
cache-control: no-storeis automatically added when cookies are present - Merges Vary headers: Multiple Vary values are deduplicated
- Prevents header leakage: Internal session data is never exposed to the browser
Working with applyResponseHeaders
TheapplyResponseHeaders helper applies the response headers to a NextResponse object:
- Multi-value headers (like
set-cookie) - Merging Vary headers
- Overriding vs. appending headers based on type
Important notes
- Use
handleAuthkitHeadersfor most cases (simpler API) - Only use this for advanced patterns like rewrites
- Always use
applyResponseHeadersto apply the response headers - Never manually forward internal headers to the browser
- The
requestHeadersmust be passed to the next handler forwithAuth()to work - Response headers are safe to send to the browser (already filtered)