Capítulo 381 de 456
NextResponse extends the Web Response API with convenience methods (json, redirect, rewrite, next, cookies) for producing responses from Proxy.
response.cookies: set, get, getAll, has, delete — mirrors NextRequest.cookies.NextResponse.json(body, init?): returns a JSON response.NextResponse.redirect(url): redirects to a given URL; commonly built from request.nextUrl.NextResponse.rewrite(url): proxies to a different URL while preserving the original URL shown to the browser.NextResponse.next(): continues routing without producing a final response; used to "pass through" in Proxy.NextResponse.next({ request: { headers } }): forwards modified request headers upstream (to the target page/route/action), not to the client.import { NextResponse } from 'next/server'
const loginUrl = new URL('/login', request.url)
loginUrl.searchParams.set('from', request.nextUrl.pathname)
return NextResponse.redirect(loginUrl)
from query param.import { type NextRequest, NextResponse } from 'next/server'
function proxy(request: NextRequest) {
const incoming = new Headers(request.headers)
const forwarded = new Headers()
for (const [name, value] of incoming) {
const headerName = name.toLowerCase()
if (!headerName.startsWith('x-') && headerName !== 'authorization' && headerName !== 'cookie') {
forwarded.set(name, value)
}
}
return NextResponse.next({ request: { headers: forwarded } })
}
| Method | Purpose |
|---|---|
json() | JSON response |
redirect() | redirect response |
rewrite() | proxy to another URL, preserve browser URL |
next() | continue routing, optionally forward request headers upstream |
NextResponse.next({ headers }): shorthand that sends headers to the client, not upstream — can override framework-critical headers like Content-Type and break Server Action submissions/streaming. Use NextResponse.next({ request: { headers } }) instead.authorization, cookie, custom x-*) to services downstream; use an allow-list.redirect/rewrite both take a URL, typically derived from request.url or request.nextUrl.next({ request: { headers } }) != next({ headers }) — the former forwards upstream, the latter exposes to the client and should be avoided.NextResponse mirrors NextRequest.cookies for symmetry.nextUrl and cookies typically read before building a NextResponse.NextResponse is constructed and returned.