Searching around gives some varied answers around the right way to return a response to an API in NextJS. I suspect some may have to do with the transition from pre-13.4 to 13.4. However, I am going to share my experiments on what worked and what is recommended.
export async function GET(request) {
// WILL EXPERIMENT WITH THESE 6 return types in 13.4
return NextResponse.json({ message: 'Hello - GET' });
return NextResponse.status(200).json({ message: 'Hello - GET' });
return Response.json({ message: 'Hello - GET' });
return Response.status(200).json({ message: 'Hello - GET' });
return NextAPIResponse.json({ message: 'Hello - GET' });
return NextAPIResponse.status(200).json({ message: 'Hello - GET' });
}
I am receiving the response through this testMethod
const testMethod = async () => {
const response = await fetch("/api/testNextJSAPI", {
method: "GET",
});
if (response.ok) {
console.log("OKAY");
} else {
console.log("ERROR");
}
};
2
Answers
In the experiment and cross referencing with docs -- the best one to use is
I'll make specific notations below because it is not the only one that actually works. Both Response and NextResponse work. And, note, attaching .status(200) never works in any case.
It does not surprise me that NextResponse and Response would have similar behavior as NextResponse extends the Web Response API as documented here.
My understanding is that NextAPIResponse is a specialized extension of node's http.ServerResponse which adds some helper methods that make it easier to send json(), set cookies, and send different response types.
And big-picture, it seems
Pages Routing -> NextAPIResponse
andApp Routing -> NextResponse
. However, I would love a higher-level view of why this switched.In order to send the status code, you need to put it in the second parameter
The difference between NextResponse and Response is that NextResponse extends the Web Response API with additional convenience methods. So it would be enough to use Web Response API if you don’t have any specific needs
Ref: https://nextjs.org/docs/app/api-reference/functions/next-response#json