Replies: 3 comments 2 replies
-
Yeah, you can't really pass type parameters to these, to make sure that you call for example And yeah, you can just use import { NextRequest, NextResponse } from "next/server";
export async function GET(request: NextRequest) {
console.log(request.nextUrl.searchParams.get("foo"));
// I guess you want to type guard that this is called with `{message: string}` shapes
return NextResponse.json({ message: "Hello, Next.js!" });
} |
Beta Was this translation helpful? Give feedback.
-
For your reference, here is an example 😄 type Response = {
message: string
}
export async function GET() {
NextResponse.json<Response>({ message: "hello" });
} |
Beta Was this translation helpful? Give feedback.
-
You can try Example Route: import { NextApiRequest } from 'next-ts-api';
// POST /api/todos
export async function POST(
request: NextApiRequest<{
title: string;
}>
) {
const { title } = await request.json();
const newTodo: Todo = {
id: Math.random().toString(),
title,
completed: false
};
return NextResponse.json(newTodo);
} API Call: import { createNextFetchApi } from "next-ts-api";
import { type ApiRoutes } from "../types/next-ts-api"; // auto generated
export const api = createNextFetchApi<ApiRoutes>();
const response = await api('todos', { // type-safe API route
method: 'POST',
body: {
title: "New Todo" // type-safe body
}
});
const newTodo = await response.json(); // type-safe return data |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Currently, API handlers have partial typescript support that makes strongly typed responses and requests easy to write. However with the new
Request
andResponse
APIs: (https://beta.nextjs.org/docs/routing/route-handlers) I'm not sure how to strongly type my endpoints.Is building a custom wrapper for Request, Response the only way to go about or is this something that Next.js 13 (beta) has already got covered?
Thanks!
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions