NextResponse
NextResponse extends theWeb Response API with additional convenience methods.
cookies
Read or mutate theSet-Cookie header of the response.
set(name, value)
Given a name, set a cookie with the given value on the response.
// Given incoming request /homelet response=NextResponse.next()// Set a cookie to hide the bannerresponse.cookies.set('show-banner','false')// Response will have a `Set-Cookie:show-banner=false;path=/home` headerreturn responseget(name)
Given a cookie name, return the value of the cookie. If the cookie is not found,undefined is returned. If multiple cookies are found, the first one is returned.
// Given incoming request /homelet response=NextResponse.next()// { name: 'show-banner', value: 'false', Path: '/home' }response.cookies.get('show-banner')getAll()
Given a cookie name, return the values of the cookie. If no name is given, return all cookies on the response.
// Given incoming request /homelet 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 responseresponse.cookies.getAll()has(name)
Given a cookie name, returntrue if the cookie exists on the response.
// Given incoming request /homelet response=NextResponse.next()// Returns true if cookie exists, false if it does notresponse.cookies.has('experiments')delete(name)
Given a cookie name, delete the cookie from the response.
// Given incoming request /homelet response=NextResponse.next()// Returns true for deleted, false if nothing is deletedresponse.cookies.delete('experiments')json()
Produce a response with the given JSON body.
import { NextResponse }from'next/server'exportasyncfunctionGET(request:Request) {returnNextResponse.json({ error:'Internal Server Error' }, { status:500 })}redirect()
Produce a response that redirects to aURL.
import { NextResponse }from'next/server'returnNextResponse.redirect(newURL('/new',request.url))TheURL can be created and modified before being used in theNextResponse.redirect() method. For example, you can use therequest.nextUrl property to get the current URL, and then modify it to redirect to a different URL.
import { NextResponse }from'next/server'// Given an incoming request...constloginUrl=newURL('/login',request.url)// Add ?from=/incoming-url to the /login URLloginUrl.searchParams.set('from',request.nextUrl.pathname)// And redirect to the new URLreturnNextResponse.redirect(loginUrl)rewrite()
Produce a response that rewrites (proxies) the givenURL while preserving the original URL.
import { NextResponse }from'next/server'// Incoming request: /about, browser shows /about// Rewritten request: /proxy, browser shows /aboutreturnNextResponse.rewrite(newURL('/proxy',request.url))next()
Thenext() method is useful for Proxy, as it allows you to return early and continue routing.
import { NextResponse }from'next/server'returnNextResponse.next()You can also forwardheaders upstream when producing the response, usingNextResponse.next({ request: { headers } }):
import { NextResponse }from'next/server'// Given an incoming request...constnewHeaders=newHeaders(request.headers)// Add a new headernewHeaders.set('x-version','123')// Forward the modified request headers upstreamreturnNextResponse.next({ request: {// New request headers headers: newHeaders, },})This forwardsnewHeaders upstream to the target page, route, or server action, and does not expose them to the client. While this pattern is useful for passing data upstream, it should be used with caution because the headers containing this data may be forwarded to external services.
In contrast,NextResponse.next({ headers }) is a shorthand for sending headers from proxy to the client. This isNOT good practice and should be avoided. Among other reasons because setting response headers likeContent-Type, can override framework expectations (for example, theContent-Type used by Server Actions), leading to failed submissions or broken streaming responses.
import {type NextRequest, NextResponse }from'next/server'asyncfunctionproxy(request:NextRequest) {constheaders=awaitinjectAuth(request.headers)// DO NOT forward headers like thisreturnNextResponse.next({ headers })}In general, avoid copying all incoming request headers because doing so can leak sensitive data to clients or upstream services.
Prefer a defensive approach by creating a subset of incoming request headers using an allow-list. For example, you might discard customx-* headers and only forward known-safe headers:
import {type NextRequest, NextResponse }from'next/server'functionproxy(request:NextRequest) {constincoming=newHeaders(request.headers)constforwarded=newHeaders()for (const [name,value]of incoming) {constheaderName=name.toLowerCase()// Keep only known-safe headers, discard custom x-* and other sensitive onesif (!headerName.startsWith('x-')&& headerName!=='authorization'&& headerName!=='cookie' ) {// Preserve original header name casingforwarded.set(name, value) } }returnNextResponse.next({ request: { headers: forwarded, }, })}Was this helpful?