
No Comments Yet
Be the first to share your thoughts and start the conversation.
Be the first to share your thoughts and start the conversation.
While developing API routes or route handlers, some common questions often come up.
In this lesson, I'll address the most frequently asked ones. If you have additional questions, don’t hesitate to reach out through our dedicated Discord channel.
Let’s dive in!
When returning data from Route Handlers in Next.js, you have two main options: new Response and NextResponse. If you take a look at our API routes, which we created not so long ago, you’ll see that we used a new Response in the api/hello-world route and NextResponse in the api/tickets route.
If you inspect the Headers of both requests, you’ll find that, by default, new Response uses text/plain, whereas since we did NextResponse.json in tickets APIs, you’ll see a content type set to application/JSON.
Both can be used effectively, but they have different use cases and features. Let's break down when to use each:
Using new Response
new Response is part of the Web API and is the standard way to create response objects in JavaScript. It's supported in Route Handlers because Next.js aims to align with Web API standards.
Use new Response when:
export async function GET() {
return new Response(JSON.stringify({ message: "Hello" }), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
}
Using NextResponse
NextResponse is a Next.js utility that extends the standard Response object with additional features specific to Next.js.
Use NextResponse when:
export async function GET() {
return NextResponse.json({ message: "Hello" }, { status: 200 });
}
So, what do we understand from this?
The first takeaway is that NextResponse.json() is a convenient method for returning JSON data as it automatically sets the Content-Type header to application/json.
The second thing would be, if you want to set cookies, you should use NextResponse for easy cookie manipulation. Know More here
export async function GET() {
const response = NextResponse.json({ message: "Hello" });
response.cookies.set("myCookie", "cookieValue");
return response;
}
Another use case is if you want to rewrite URLs or redirect them to some other destination, you can use NextResponse to handle it
NextResponse.rewrite() allows you to internally rewrite the URL without changing the URL in the browser. Know More here
export async function GET() {
return NextResponse.rewrite(new URL("/new-destination", request.url));
}
NextResponse.redirect() provides an easy way to perform redirects. Know More here
export async function GET() {
return NextResponse.redirect(new URL("/new-page", request.url));
}
In general, it's recommended to use NextResponse in Next.js applications, especially when working with Route Handlers. It provides a more convenient API and access to Next.js-specific features while still being compatible with the Web API standards.
However, if you're writing code that needs to be portable across different environments or if you're working on a part of your application that might be separated from Next.js in the future, using new Response could be a better choice for its standard compliance and portability.
Remember, both new Response and NextResponse are fully supported in Route Handlers, so you can choose the one that best fits your specific use case and coding style.
Similar to what we discussed about Response types we can use, we also have two different Request types in Next.js: Request and NextRequest
Again, not so long ago, we used both request types in Route Handlers like this
It isn’t like we can not use Request for search API routes. We can do it; it’s completely possible.
Both can be used effectively, but they have different features and use cases. Let's break down when to use each:
Using Request
Request is part of the standard Web API and is supported in Next.js Route Handlers as part of the framework's alignment with Web standards.
Use Request when (similar to new Response):
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id') const id = searchParams.get('id')
}
Using NextRequest
NextRequest is a Next.js-specific extension of the standard Request object. It provides additional methods and properties that are useful in the context of Next.js applications .
Use NextRequest when:
export async function GET(request: NextRequest) {
const id = request.nextUrl.searchParams.get("id");
const cookie = request.cookies.get("myCookie");
}
It is the same thing that we discussed in the previous question about Response and NextResponse.
You can choose whichever you want for whichever use case you prefer, as both are fully supported in Route Handlers.
Complete source code of this lesson is available at