如何在 Next.js 中修改请求标头

aiw*_*aiw 14 javascript next.js

我需要为服务器的每个请求添加标头。

我使用_middleware来做到这一点,如下所示:

export async function middleware(req: NextRequest): Promise<NextResponse> {
    req.headers.append('x-custom-header', '1337');
    return NextResponse.next();
}
Run Code Online (Sandbox Code Playgroud)

如果我这样做,console.log(req.headers)我会看到请求标头已添加:

BaseHeaders [Headers] {
    [Symbol(map)]: {
      accept: [ '*/*' ],
      'accept-encoding': [ 'gzip, deflate, br' ],
      'accept-language': [ 'en-GB,en-US;q=0.9,en;q=0.8' ],
      'cache-control': [ 'no-cache' ],
      connection: [ 'keep-alive' ],
      cookie: ...,
      host: ...,
      pragma: [ 'no-cache' ],
      referer: ...,
      ...,
      'x-custom-header': [ '1337' ]
    }
  }
Run Code Online (Sandbox Code Playgroud)

但是,这不会修改请求:浏览器中没有请求标头。

为什么请求没有被修改?是否有其他方法可以修改 Next.js 中的请求标头?

mak*_*asy 10

看起来从 Next.js v13.0.0 开始,现在可以修改请求标头: https: //nextjs.org/docs/advanced-features/middleware#setting-headers

这是文档中的代码片段:

// middleware.ts

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
}
Run Code Online (Sandbox Code Playgroud)


Hug*_*hes 0

您可以通过添加安全标头以类似的方式添加自定义标头,方法headers是在您的next.config.js

// next.config.js

// You can choose which headers to add to the list
// after learning more below.
const securityHeaders = []

module.exports = {
  async headers() {
    return [
      {
        // Apply these headers to all routes in your application.
        source: '/:path*',
        headers: securityHeaders,
      },
    ]
  },
}
Run Code Online (Sandbox Code Playgroud)

  • 此方法适用于响应标头,但我需要更改请求标头。 (6认同)