next/server

next/serverprovides server-only helpers for use inMiddlewareandEdge API Routes.

NextRequest

TheNextRequestobject is an extension of the nativeRequestopen in new windowinterface, with the following added methods and properties:

  • cookies- ARequestCookiesopen in new windowinstance with cookies from theRequest. It reads/mutates theCookieheader of the request. See alsoUsing cookies in Middleware.- get- A method that takes a cookienameand returns an object withnameandvalue. If a cookie withnameisn't found, it returnsundefined. If multiple cookies match, it will only return the first match.- getAll- A method that is similar toget, but returns a list of all the cookies with a matchingname. Ifnameis unspecified, it returns all the available cookies.- set- A method that takes an object with properties ofCookieListItemas defined in theW3C CookieStore APIopen in new windowspec.- delete- A method that takes either a cookienameor a list of names. and removes the cookies matching the name(s). Returnstruefor deleted andfalsefor undeleted cookies.- has- A method that takes a cookienameand returns abooleanbased on if the cookie exists (true) or not (false).- clear- A method that takes no argument and will effectively remove theCookieheader.- nextUrl: Includes an extended, parsed, URL object that gives you access to Next.js specific properties such aspathname,basePath,trailingSlashandi18n. Includes the following properties:- basePath(string)- buildId(string || undefined)- defaultLocale(string || undefined)- domainLocale- defaultLocale: (string)- domain: (string)- http: (boolean || undefined)- locales: (string[] || undefined)- locale(string || undefined)- url(URL)- ip: (string || undefined) - Has the IP address of theRequest. This information is provided by your hosting platform.- geo- Has the geographic location from theRequest. This information is provided by your hosting platform. Includes the following properties:- city(string || undefined)- country(string || undefined)- region(string || undefined)- latitude(string || undefined)- longitude(string || undefined)

You can use theNextRequestobject as a direct replacement for the nativeRequestinterface, giving you more control over how you manipulate the request.

NextRequestcan be imported fromnext/server:

import type { NextRequest } from 'next/server'

NextFetchEvent

TheNextFetchEventobject extends the nativeFetchEventopen in new windowobject, and includes thewaitUntil()open in new windowmethod.

ThewaitUntil()method can be used to prolong the execution of the function if you have other background work to make.

import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest } from 'next/server'

export async function middleware(req: NextRequest, event: NextFetchEvent) {
  event.waitUntil(
    fetch('https://my-analytics-platform.com', {
      method: 'POST',
      body: JSON.stringify({ pathname: req.nextUrl.pathname }),
    })
  )

  return NextResponse.next()
}

TheNextFetchEventobject can be imported fromnext/server:

import type { NextFetchEvent } from 'next/server'

NextResponse

TheNextResponseclass extends the nativeResponseopen in new windowinterface, with the following:

Public Methods

Public methods are available on an instance of theNextResponseclass. Depending on your use case, you can create an instance and assign to a variable, then access the following public methods:

  • cookies- AResponseCookiesopen in new windowinstance with the cookies from theResponse. It a AResponseCooiesopen in new windowinstance with cookies from theResponse. It reads/mutates theSet-Cookieheader of the response. See alsoUsing cookies in Middleware.- get- A method that takes a cookienameand returns an object withnameandvalue. If a cookie withnameisn't found, it returnsundefined. If multiple cookies match, it will only return the first match.- getAll- A method that is similar toget, but returns a list of all the cookies with a matchingname. Ifnameis unspecified, it returns all the available cookies.- set- A method that takes an object with properties ofCookieListItemas defined in theW3C CookieStore APIopen in new windowspec.- delete- A method that takes either a cookienameor a list of names. and removes the cookies matching the name(s). Returnstruefor deleted andfalsefor undeleted cookies.

Static Methods

The following static methods are available on theNextResponseclass directly:

  • redirect()- Returns aNextResponsewith a redirect set- rewrite()- Returns aNextResponsewith a rewrite set- next()- Returns aNextResponsethat will continue the middleware chain

To use the methods above,you must return theNextResponseobjectreturned.NextResponsecan be imported fromnext/server:

import { NextResponse } from 'next/server'

userAgent

TheuserAgenthelper allows you to interact with the user agent object from the request. It is abstracted from the nativeRequestobject, and is an opt in feature. It has the following properties:

  • isBot: (boolean) Whether the request comes from a known bot- browser- name: (string || undefined) The name of the browser- version: (string || undefined) The version of the browser, determined dynamically- device- model: (string || undefined) The model of the device, determined dynamically- type: (string || undefined) The type of the browser, can be one of the following values:console,mobile,tablet,smarttv,wearable,embedded, orundefined- vendor: (string || undefined) The vendor of the device, determined dynamically- engine- name: (string || undefined) The name of the browser engine, could be one of the following values:Amaya,Blink,EdgeHTML,Flow,Gecko,Goanna,iCab,KHTML,Links,Lynx,NetFront,NetSurf,Presto,Tasman,Trident,w3m,WebKitorundefined- version: (string || undefined) The version of the browser engine, determined dynamically, orundefined- os- name: (string || undefined) The name of the OS, could beundefined- version: (string || undefined) The version of the OS, determined dynamically, orundefined- cpu- architecture: (string || undefined) The architecture of the CPU, could be one of the following values:68k,amd64,arm,arm64,armhf,avr,ia32,ia64,irix,irix64,mips,mips64,pa-risc,ppc,sparc,sparc64orundefined

userAgentcan be imported fromnext/server:

import { userAgent } from 'next/server'

import { NextRequest, NextResponse, userAgent } from 'next/server'

export function middleware(request: NextRequest) {
  const url = request.nextUrl
  const { device } = userAgent(request)
  const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
  url.searchParams.set('viewport', viewport)
  return NextResponse.rewrite(url)
}

FAQ

Why does redirect use 307 and 308?

When usingredirect()you may notice that the status codes used are307for a temporary redirect, and308for a permanent redirect. While traditionally a302was used for a temporary redirect, and a301for a permanent redirect, many browsers changed the request method of the redirect, from aPOSTtoGETrequest when using a302, regardless of the origins request method.

Taking the following example of a redirect from/usersto/people, if you make aPOSTrequest to/usersto create a new user, and are conforming to a302temporary redirect, the request method will be changed from aPOSTto aGETrequest. This doesn't make sense, as to create a new user, you should be making aPOSTrequest to/people, and not aGETrequest.

The introduction of the307status code means that the request method is preserved asPOST.

  • 302- Temporary redirect, will change the request method fromPOSTtoGET- 307- Temporary redirect, will preserve the request method asPOST

Theredirect()method uses a307by default, instead of a302temporary redirect, meaning your requests willalwaysbe preserved asPOSTrequests.

If you want to cause aGETresponse to aPOSTrequest, use303.

Learn moreopen in new windowabout HTTP Redirects.

How do I access Environment Variables?

process.envcan be used to accessEnvironment Variablesfrom Edge Middleware. They are evaluated duringnext build:

上次更新:
Loading...