Next.jsMedium

What is the NextRequest and NextResponse API?

NextRequest and NextResponse from next/server extend the Web Request and Response classes with Next.js conveniences: parsed URL access (nextUrl), a cookies API, and response helpers such as redirect, rewrite, next and json. They are used in Route Handlers and especially in proxy.ts.

NextRequest

  • request.nextUrl: an extended URL with pathname, searchParams, basePath and (Pages Router i18n) locale. Clone and modify it to build redirect targets.
  • request.cookies: get, getAll, set, delete, has, clear.
  • Everything from Request: headers, method, json(), formData(), text().

NextResponse

  • NextResponse.json(body, init): a JSON response.
  • NextResponse.redirect(url, status?): 307 by default; must be an absolute URL (new URL("/login", request.url)).
  • NextResponse.rewrite(url): serve a different route while keeping the browser URL. Used in Proxy.
  • NextResponse.next(init): continue routing from Proxy, optionally with modified request headers via { request: { headers } }.
  • response.cookies.set/delete: set cookies on the outgoing response.

Related helpers

  • userAgent(request) from next/server parses device, browser and bot info.
  • NextFetchEvent.waitUntil() (second argument in Proxy) keeps work running after the response.
  • NextProxy type for typing the proxy function.

When to use plain Request/Response

In Route Handlers, plain Web types are enough unless you need nextUrl or the cookies helpers. Plain types keep code portable to other runtimes.

Pitfall

NextResponse.next({ headers }) sets response headers visible to the client; to pass data upstream, set NextResponse.next({ request: { headers } }).

Code example

tsx
1// proxy.ts
2import { NextResponse, userAgent } from "next/server";
3import type { NextRequest } from "next/server";
4
5export function proxy(request: NextRequest) {
6 const { pathname, searchParams } = request.nextUrl;
7
8 // Redirect: absolute URL built from the request
9 if (pathname === "/old-pricing") {
10 return NextResponse.redirect(new URL("/pricing", request.url), 308);
11 }
12
13 // Rewrite mobile users to a different page, URL stays the same
14 if (userAgent(request).device.type === "mobile" && pathname === "/") {
15 return NextResponse.rewrite(new URL("/mobile", request.url));
16 }
17
18 // Continue, passing data upstream through a request header
19 const requestHeaders = new Headers(request.headers);
20 requestHeaders.set("x-campaign", searchParams.get("utm_campaign") ?? "none");
21 const response = NextResponse.next({ request: { headers: requestHeaders } });
22 response.cookies.set("seen", "1", { path: "/" });
23 return response;
24}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app