Skip to content

Accept generic type parameters for NextResponse #45943

@karlhorky

Description

@karlhorky

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

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

  1. Arguably, the NextRequest 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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    TypeScriptRelated to types with Next.js.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions