#save key in http header
1 messages · Page 1 of 1 (latest)
Hi @obtuse forge. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can set HTTP headers in several ways. Here are a few examples:
- Using
NextResponsein Middleware: You can set request and response headers using theNextResponseAPI in your middleware. Here's an example:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-hello-from-middleware1', 'hello')
// You can also set request headers in NextResponse.rewrite
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello')
return response
}
Source (https://nextjs.org/docs/app/building-your-application/routing/middleware)
- Using
headerskey innext.config.js: You can set custom HTTP headers using theheaderskey innext.config.js. Here's an example:
module.exports = {
async headers() {
return [
{
source: '/about',
headers: [
{
key: 'x-custom-header',
value: 'my custom header value',
},
{
key: 'x-another-custom-header',
value: 'my other custom header value',
},
],
},
]
},
}
Source (https://nextjs.org/docs/app/api-reference/next-config-js/headers)
- Using
headersin Route Handlers: You can read headers withheadersfromnext/headersin a Route Handler. To set headers, you need to return a newResponsewith newheaders.
import { headers } from 'next/headers'
export async function GET(request: Request) {
const headersList = headers()
const referer = headersList.get('referer')
return new Response('Hello, Next.js!', {
status: 200,
headers: { referer: referer },
})
}
Source (https://nextjs.org/docs/app/building-your-application/routing/router-handlers)