I have a dynamic API route file for the POST request. Here is the code of that file:
import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/dbConnect";
import User from "@/models/User";
export async function POST(req: NextRequest, res: NextResponse) {
const data = await req.json();
const { name, email, password, country } = data;
await dbConnect();
try {
const user = await User.create({
name, email, password, country
})
return NextResponse.json({
success: true,
data: user,
}, {
status: 201,
})
} catch (error) {
return NextResponse.json({
success: false,
}, {
status: 400,
})
}
}
If I try to replace NextResponse
inside the route with res
, it gives me an error. Here’s what I mean:
return res.json({
success: true,
data: user,
}, {
status: 201,
})
Here’s the error that it’s giving me: Expected 0 arguments, but got 2.ts(2554)
.
Why I can’t replace NextResponse
with res
?
2
Answers
If you need to use
res
for your use-case, you can use:Do note that
res
must be of typeNextApiResponse
and notNextResponse
.Since you have that
export async function POST
, you are most likely using the newapp
router (directory), and there, an API route gets passed as parameter only therequest
.To send a response back, you have to return a
Response
or useNextResponse
fromnext/server
, for example:The
res
of typeNextApiResponse
goes withreq
of typeNextApiRequest
, but they are for API routes in the initialpages
router (directory).