next/server
next/server
provides server-only helpers for use inMiddlewareandEdge API Routes.
NextRequest
TheNextRequest
object is an extension of the nativeRequest
interface, with the following added methods and properties:
cookies
- ARequestCookiesinstance with cookies from theRequest
. It reads/mutates theCookie
header of the request. See alsoUsing cookies in Middleware.-get
- A method that takes a cookiename
and returns an object withname
andvalue
. If a cookie withname
isn'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
. Ifname
is unspecified, it returns all the available cookies.-set
- A method that takes an object with properties ofCookieListItem
as defined in theW3C CookieStore APIspec.-delete
- A method that takes either a cookiename
or a list of names. and removes the cookies matching the name(s). Returnstrue
for deleted andfalse
for undeleted cookies.-has
- A method that takes a cookiename
and returns aboolean
based on if the cookie exists (true
) or not (false
).-clear
- A method that takes no argument and will effectively remove theCookie
header.-nextUrl
: Includes an extended, parsed, URL object that gives you access to Next.js specific properties such aspathname
,basePath
,trailingSlash
andi18n
. 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 theNextRequest
object as a direct replacement for the nativeRequest
interface, giving you more control over how you manipulate the request.
NextRequest
can be imported fromnext/server
:
import type { NextRequest } from 'next/server'
NextFetchEvent
TheNextFetchEvent
object extends the nativeFetchEvent
object, and includes thewaitUntil()
method.
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()
}
TheNextFetchEvent
object can be imported fromnext/server
:
import type { NextFetchEvent } from 'next/server'
NextResponse
TheNextResponse
class extends the nativeResponse
interface, with the following:
Public Methods
Public methods are available on an instance of theNextResponse
class. Depending on your use case, you can create an instance and assign to a variable, then access the following public methods:
cookies
- AResponseCookiesinstance with the cookies from theResponse
. It a AResponseCooiesinstance with cookies from theResponse
. It reads/mutates theSet-Cookie
header of the response. See alsoUsing cookies in Middleware.-get
- A method that takes a cookiename
and returns an object withname
andvalue
. If a cookie withname
isn'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
. Ifname
is unspecified, it returns all the available cookies.-set
- A method that takes an object with properties ofCookieListItem
as defined in theW3C CookieStore APIspec.-delete
- A method that takes either a cookiename
or a list of names. and removes the cookies matching the name(s). Returnstrue
for deleted andfalse
for undeleted cookies.
Static Methods
The following static methods are available on theNextResponse
class directly:
redirect()
- Returns aNextResponse
with a redirect set-rewrite()
- Returns aNextResponse
with a rewrite set-next()
- Returns aNextResponse
that will continue the middleware chain
To use the methods above,you must return theNextResponse
objectreturned.NextResponse
can be imported fromnext/server
:
import { NextResponse } from 'next/server'
userAgent
TheuserAgent
helper allows you to interact with the user agent object from the request. It is abstracted from the nativeRequest
object, 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
,WebKit
orundefined
-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
,sparc64
orundefined
userAgent
can 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 are307
for a temporary redirect, and308
for a permanent redirect. While traditionally a302
was used for a temporary redirect, and a301
for a permanent redirect, many browsers changed the request method of the redirect, from aPOST
toGET
request when using a302
, regardless of the origins request method.
Taking the following example of a redirect from/users
to/people
, if you make aPOST
request to/users
to create a new user, and are conforming to a302
temporary redirect, the request method will be changed from aPOST
to aGET
request. This doesn't make sense, as to create a new user, you should be making aPOST
request to/people
, and not aGET
request.
The introduction of the307
status code means that the request method is preserved asPOST
.
302
- Temporary redirect, will change the request method fromPOST
toGET
-307
- Temporary redirect, will preserve the request method asPOST
Theredirect()
method uses a307
by default, instead of a302
temporary redirect, meaning your requests willalwaysbe preserved asPOST
requests.
If you want to cause aGET
response to aPOST
request, use303
.
Learn moreabout HTTP Redirects.
How do I access Environment Variables?
p
can be used to accessEnvironment Variablesfrom Edge Middleware. They are evaluated duringnext build
: