next.js 我需要在我的下一个js应用程序中添加安全头

pgccezyw  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(117)

我有一个下一个js应用程序,我需要在next.config.js文件中添加安全头
这是我现在的代码

// eslint-disable-next-line @typescript-eslint/no-var-requires
const semi = require("@douyinfe/semi-next").default({})
/** @type {import('next').NextConfig} */
const nextConfig = semi({
output: "export",
assetPrefix: ".",
transpilePackages: [
"@douyinfe/semi-ui",
"@douyinfe/semi-icons",
"@douyinfe/semi-illustrations",
],
typescript: {
 ignoreBuildErrors: true
},
eslint: {
ignoreDuringBuilds: true
}
})

module.exports = nextConfig

我还要加上这个

async headers() {
  return [
    {
      source: "/(.*)?",
      headers: [
        {
          key: "X-Frame-Options",
          value: "DENY",
        },
        {
          key: "X-Content-Type-Options",
          value: "nosniff",
        },
        {
          key: "Referrer-Policy",
          value: "origin-when-cross-origin",
        },
      ],
    },
  ];
},

但是如果我在代码中添加这个,它会抛出错误,我得到这个错误-“当输出选项设置为“导出”时,不能使用头属性。”
如果我删除output:“export”选项,它可以工作,但我不能删除output:“export”选项,因为它对我的应用程序很重要。请建议一种方法来添加标题在我的申请

xn1cxnb4

xn1cxnb41#

你可以使用中间件来为你的请求添加头部,在你的middleware.js中使用以下示例代码:

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
}

查看文档:
https://nextjs.org/docs/pages/building-your-application/routing/middleware#setting-headers

相关问题