Next 配置项 next.config.js

headers

headers 可以在请求头添加一些自定义内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const nextConfig = {
headers: async () => {
return [
{
source: '/about/:id',
headers: [
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
},
{
key: 'ID',
value: ':id'
},
]
}
]
}
}

module.exports = nextConfig

headers 是一个异步函数,source 代表路径,headers 是一个数组,数组中可以添加多个 [key, value] 的属性,并且还可以获取路由参数进行赋值,例如 :id

headers 同名属性会覆盖前面的属性。

header 的对象属性有哪些

source

请求路径,支持三种模式

  • 路径匹配 source: '/about/:id' 会匹配 about 下一层级路径,多层的不行,例如 /about/1/detail 匹配不到
  • 通配符匹配 source: '/about/:id*' 在路径匹配基础上,支持匹配多层路径,例如 /about/1/detail 可以匹配到
  • 正则匹配 source: '/about/:id(\\d+)' 支持正则匹配,例如 /about/1/detail 可以匹配到。另外要注意 (、)、 {、 }、 :、 *、 +、 ? 等特殊字符需要转义

basePath

basePath 可选值为 false | undefined,当值设置为 false,source 在匹配时会忽略 basePath,使用 Link 跳转会自动加上 basePath

has

匹配某些情况才设置 header

对象属性

  • type 类型,可选值为 header | cookie | host | query,header 为请求头,cookie 为请求头的 Cookie,host 为 主机名+端口号,query 为 query参数
  • key 所选类型的 key
  • value 所选类型的 value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const nextConfig = {
headers: async () => {
return [
{
source: '/about',
has: [
{
type: 'query',
key: 'name',
},
],
headers: [
// ...
],
}
]
}
}

module.exports = nextConfig

以上代码就是当地址中存在 name 参数时,才会设置 header

missing

用法同 has,区别在于 missing 是不满足条件时,才设置 header

redirects

一个异步函数,用于进行重定向

属性

  • source 匹配路径
  • destination 重定向路径
  • permanent 是否永久重定向,可选值为 true | false,默认为 false,即临时重定向,307 状态码,当设置为 true 时,即永久重定向,308 状态码

为什么 Next 使用 307 状态码,而不是 302 状态码?

很多浏览器会将重定向的请求方法修改为 GET,而不管原本的方法是什么。举个例子,如果浏览器发送了一个 POST 请求,/v1/users ,然后返回了 302 状态码,新地址是 /v2/users,则后续的请求会是 GET /V2/users 而不是 POST /v2/users,Next.js 用 307 临时重定向和 308 永久重定向状态码就是为了显示保留之前使用的请求方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
const nextConfig = {
redirects: async () => {
return [
{
source: '/about/:id',
destination: '/',
permanent: true
}
]
}
}

module.exports = nextConfig

重定向会在文件系统(包括页面和 /public 文件)之前被触发。

重定向不会应用于客户端路由(Link、router.push),除非使用了中间件,且有匹配的路径。

当应用重定向的时候,请求路径的参数也会传递给重定向目标路径:

在 redirect 中也可以使用 basePath、has、missing 等属性,用法同 headers。

// 未完待续…


Next 配置项 next.config.js
https://l1ushun.github.io/2024/09/04/next-05/
作者
liu shun
发布于
2024年9月4日