为何在Next.js API路由中无法使用类型为NextResponse的res?
res.json() throws an error in Next.js App Router API routes The error happens because of a core difference in how response handling works between Next.js's App Router (your current setup) and the older Pages Router:
resin App Router isn't an Express-style response object
In App Router API routes, when you receiveres: NextResponseas a parameter, this is an immutable response instance—not the mutable, writable response stream used in Pages Router. Thejson()method on aNextResponseinstance doesn't accept arguments (it’s not designed to send new data); thejson()method you’re trying to use is actually the static methodNextResponse.json(), which creates a new response object from your data.Wrong vs Correct Usage
- Incorrect (triggers your error):
export async function POST(req: NextRequest, res: NextResponse) { // Error: Expected 0 arguments, but got 2 res.json({ message: "Success" }, { status: 200 }); } - Correct (standard App Router pattern):
import { NextRequest, NextResponse } from "next/server"; export async function POST(req: NextRequest) { // Return a new NextResponse directly return NextResponse.json({ message: "Success" }, { status: 200 }); } - If you need to modify an existing
resinstance (rare for most use cases), clone it with your desired changes:export async function POST(req: NextRequest, res: NextResponse) { return res.clone({ body: JSON.stringify({ message: "Success" }), status: 200 }); }
- Incorrect (triggers your error):
Key Takeaway
App Router API routes are built to return response objects directly instead of mutating aresstream. The Express-styleres.json(data)pattern only works in Pages Router; in App Router, use the staticNextResponse.json()method to generate and return your JSON response.
内容的提问来源于stack exchange,提问作者in43sh

