Next.js Discord

Discord Forum

next.js 13 App Router: API endpoint type infered

Answered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I want to create a typescript type from the returned payload of app router api endpoints.

For example:
export async function POST(request: NextRequest) { return Response.json({ messages: [/** message objects **/], }); }

// would be infered here {messages: Array<Message>}
export type POSTData = / some typescript magic /

// used in the client
const messages: POSTData = await getPostEndpoint();
Answered by Barbary Lion
Here is a solution if you can use NextResponse for your return type:
export type ExtractResponseType<T extends (...args: any) => any> = Awaited<ReturnType<T>> extends NextResponse<infer R> ? R : never;
View full answer

7 Replies

@Double-striped Thick-knee typescript cannot directly infer types from Response objects, so you'll need to define them manually.
Barbary LionOP
Here is a solution if you can use NextResponse for your return type:
export type ExtractResponseType<T extends (...args: any) => any> = Awaited<ReturnType<T>> extends NextResponse<infer R> ? R : never;
Answer
Barbary LionOP
example usage:
export type PostData = ExtractResponseType<typeof POST>;
I'm closing this because I wanted to infer a type from a POST (doesnt matter the app router api endpoint type though) from a request, which I was able to do with the above approach. I didn't find a way to type the Response approach
@Double-striped Thick-knee didn't know about it, thanks
Barbary LionOP
your response made me realize I could use NextResponse, appreciate the assistance 🙏