Next.js Discord

Discord Forum

Typed API routes from GET method?

Answered
Mini Rex posted this in #help-forum
Open in Discord
Mini RexOP
Hey Everyone, has anyone had success with getting the return types for Typescript, from an API route?

Let say I have this data:

export async function GET(request: Request) {
  return Response.json({
    data: {
      test: 'string',
    },
  });
}


When calling the route, how to get typed response from the route fetch?
Tried the following without any luck:

import { GET } from "@/app/api/route";
import { NextResponse } from "next/server";

type TypedResponse =
  ReturnType<typeof GET> extends NextResponse<infer T> ? T : never;
Answered by joulev
nope, impossible. Response is a generic class, you can get literally anything from a Response object not necessarily just json, so implementing a TypedResponse is not possible.

if you want type-safe api routes just use trpc https://trpc.io
View full answer

2 Replies