applyResponseHeaders function applies AuthKit response headers to a Next.js NextResponse object. This low-level utility is used when creating custom middleware responses with rewrites or advanced routing.
Most users should use
handleAuthkitHeaders instead, which handles both request and response headers automatically. Use applyResponseHeaders only for advanced use cases like rewrites.Function signature
Parameters
The Next.js response object to modify.
The response headers from
partitionAuthkitHeaders containing only allowlisted headers safe for the browser.Returns
The same response object with headers applied. The function mutates the response and returns it for convenience.
Header merging behavior
The function properly merges headers according to their type:- Multi-value headers (
Set-Cookie,Link, etc.) - Appends values instead of replacing - Vary header - Merges unique values with comma separation
- Other headers - Sets or replaces the value
Examples
Basic usage with rewrites
Dynamic routing with session data
Custom response with headers
Which headers are applied?
The function applies only allowlisted response headers:| Header | Purpose |
|---|---|
Set-Cookie | Session cookies (appended, not replaced) |
Cache-Control | Caching directives for authenticated responses |
Vary | Cache variation keys (merged) |
WWW-Authenticate | Authentication challenges |
Proxy-Authenticate | Proxy authentication |
Link | Pagination, preload hints (appended) |
x-middleware-cache | Next.js middleware caching control |
When to use this function
UseapplyResponseHeaders when you need:
Rewrites
Rewrites
Creating
NextResponse.rewrite() responses that need AuthKit headers.Custom responses
Custom responses
Building JSON, image, or other custom responses that should include session cookies.
Manual header control
Manual header control
Full control over response creation while still properly applying AuthKit headers.
Related resources
handleAuthkitHeaders
High-level helper for most use cases
partitionAuthkitHeaders
Separate request and response headers
Composable middleware
Complete middleware composition guide