#type safe api routes
1 messages · Page 1 of 1 (latest)
Hi @fluid bridge. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can make your API routes more type-safe by importing the NextApiRequest and NextApiResponse types from next. You can also type your response data. Here's an example:
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
In the above example, ResponseData is a type that describes the shape of the response data. This makes your API routes more type-safe as TypeScript can now check that the data you're sending matches the ResponseData type.
However, if you're using the App Router in Next.js, API Routes have been replaced by Route Handlers. You can create custom request handlers for a given route using the Web Request and Response APIs. Here's an example:
export async function GET(request: Request) {}
In this case, you would need to manually type the request and response objects for each route handler. Unfortunately, there's no way to avoid this if you want type safety.
Remember, the body of NextApiRequest is any because the client may include any payload. You should validate the type/shape of the body at runtime before using it.
Sources:
- Adding TypeScript types (https://nextjs.org/docs/pages/building-your-application/routing/api-routes#adding-typescript-types)
- API Routes (https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#api-routes)