Capítulo 381 de 456

NextResponse

Core Idea

NextResponse extends the Web Response API with convenience methods (json, redirect, rewrite, next, cookies) for producing responses from Proxy.

Key Concepts

  • 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.

Code Examples

import { NextResponse } from 'next/server'

const loginUrl = new URL('/login', request.url)
loginUrl.searchParams.set('from', request.nextUrl.pathname)
return NextResponse.redirect(loginUrl)
  • O que demonstra: building a redirect URL with a 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 } })
}
  • O que demonstra: allow-list pattern for safely forwarding only known-safe headers.

Reference Tables

MethodPurpose
json()JSON response
redirect()redirect response
rewrite()proxy to another URL, preserve browser URL
next()continue routing, optionally forward request headers upstream

Anti-patterns

  • 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.
  • Blindly copying all incoming request headers upstream: risks leaking sensitive data (authorization, cookie, custom x-*) to services downstream; use an allow-list.

Key Takeaways

  1. redirect/rewrite both take a URL, typically derived from request.url or request.nextUrl.
  2. next({ request: { headers } }) != next({ headers }) — the former forwards upstream, the latter exposes to the client and should be avoided.
  3. Cookie API on NextResponse mirrors NextRequest.cookies for symmetry.

Connects To

  • NextRequest: source of nextUrl and cookies typically read before building a NextResponse.
  • Proxy: the primary place NextResponse is constructed and returned.