跳至内容
API 参考函数NextResponse

NextResponse

NextResponse 扩展了 Web Response API,并提供了一些额外的便利方法。

cookies

读取或修改响应的 Set-Cookie 头部。

set(name, value)

给定一个名称,在响应中设置具有给定值的 cookie。

// Given incoming request /home
let response = NextResponse.next()
// Set a cookie to hide the banner
response.cookies.set('show-banner', 'false')
// Response will have a `Set-Cookie:show-banner=false;path=/home` header
return response

get(name)

给定一个 cookie 名称,返回 cookie 的值。如果找不到 cookie,则返回 undefined。如果找到多个 cookie,则返回第一个 cookie。

// Given incoming request /home
let response = NextResponse.next()
// { name: 'show-banner', value: 'false', Path: '/home' }
response.cookies.get('show-banner')

getAll()

给定一个 cookie 名称,返回 cookie 的值。如果没有给出名称,则返回响应中的所有 cookie。

// Given incoming request /home
let response = NextResponse.next()
// [
//   { name: 'experiments', value: 'new-pricing-page', Path: '/home' },
//   { name: 'experiments', value: 'winter-launch', Path: '/home' },
// ]
response.cookies.getAll('experiments')
// Alternatively, get all cookies for the response
response.cookies.getAll()

delete(name)

给定一个 cookie 名称,从响应中删除该 cookie。

// Given incoming request /home
let response = NextResponse.next()
// Returns true for deleted, false is nothing is deleted
response.cookies.delete('experiments')

json()

生成具有给定 JSON 主体的响应。

app/api/route.ts
import { NextResponse } from 'next/server'
 
export async function GET(request: Request) {
  return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}

redirect() URL的响应。

import { NextResponse } from 'next/server'
 
return NextResponse.redirect(new URL('/new', request.url))

在使用NextResponse.redirect()方法之前,可以创建和修改URL。例如,您可以使用request.nextUrl属性获取当前 URL,然后修改它以重定向到其他 URL。

import { NextResponse } from 'next/server'
 
// Given an incoming request...
const loginUrl = new URL('/login', request.url)
// Add ?from=/incoming-url to the /login URL
loginUrl.searchParams.set('from', request.nextUrl.pathname)
// And redirect to the new URL
return NextResponse.redirect(loginUrl)

rewrite()

生成一个重写(代理)给定URL的响应,同时保留原始 URL。

import { NextResponse } from 'next/server'
 
// Incoming request: /about, browser shows /about
// Rewritten request: /proxy, browser shows /about
return NextResponse.rewrite(new URL('/proxy', request.url))

next()

next()方法对 Middleware 很有用,因为它允许您提前返回并继续路由。

import { NextResponse } from 'next/server'
 
return NextResponse.next()

您还可以转发生成响应时的headers

import { NextResponse } from 'next/server'
 
// Given an incoming request...
const newHeaders = new Headers(request.headers)
// Add a new header
newHeaders.set('x-version', '123')
// And produce a response with the new headers
return NextResponse.next({
  request: {
    // New request headers
    headers: newHeaders,
  },
})