-
Notifications
You must be signed in to change notification settings - Fork 29.5k
Description
Describe the feature you'd like to request
Hi, first of all thanks for your amazing effort on Next.js, great framework 🙌
With the new App Routes coming courtesy of @wyattjoh, @ijjk and @timneutkens with the merge + publish to canary
of #45716, the following pattern is now possible in an App Route for eg. an API handler:
import { NextRequest, NextResponse } from 'next/server';
type RequestBody = { zzz: number };
type ResponseBody = { abc: number };
export async function POST(request: NextRequest) {
const body: RequestBody = await request.json();
return NextResponse.json({
abc: 123, // ❌ POST function return type cannot check type of response body object
});
}
These are using the NextRequest
and NextResponse
types created by @javivelasco and others.
But the ResponseBody
type are not able to be checked easily here.
Ideally, NextResponse
would accept generic type parameters (just like the NextApiResponse
type currently does for API routes in the pages/api/
directory).
Describe the solution you'd like
It would be amazing to be able to pass generic type parameters into the NextResponse
type, enabling a pattern like this:
import { NextRequest, NextResponse } from 'next/server';
type RequestBody = { zzz: number };
type ResponseBody = { abc: number };
export async function POST(request: NextRequest<RequestBody>): NextResponse<ResponseBody> {
const body: RequestBody = await request.json();
return NextResponse.json({
abc: 123, // ✅ POST function return type checks type of response body object
});
}
Prior Art
NextApiResponse
for API routes inpages/api/
directory: Improve NextApiResponse typing #7841 by @VincentCordobes (reviewed by @Timer and @huv1k)@types/express
:Request
andResponse
types - which both accept a generic type parameter for the body
Caveats
Edit: Removed this section, because this issue was originally about allowing generic type parameters with NextRequest
as well, but this has since changed to only encompass NextResponse
Arguably, theNextRequest
body is unknown until runtime, so this is better handled instead with Zod or some other runtime validation. But for quick/simple projects without this validation, it's nice to be able to type the request body type.
Describe alternatives you've considered
An alternative would be for TypeScript to make the Response
and Request
interfaces accept generic type parameters:
However, this may be unlikely to happen - a similar suggestion for FormData
has been not implemented since 2021: