一覧へ戻る
richardsolomou/next-safe-route(新しいタブで開きます)
主要言語: TypeScript
Type-safe and validated Route Handlers for Next.js
- star 数
- 37
- watcher 数
- 1
- fork 数
- 8
- issue 数
- 6
- 最終更新
- 2025/09/23
主要言語: TypeScript
Type-safe and validated Route Handlers for Next.js
next-safe-route is a utility library for Next.js that provides type-safety and schema validation for Route Handlers/API Routes.
npm install next-safe-route
The library natively works with zod for schema validation, but you can use any other validation library that is supported by TypeSchema, as long as you install its respective adapter.
// app/api/hello/route.ts import { createSafeRoute } from 'next-safe-route'; import { z } from 'zod'; const paramsSchema = z.object({ id: z.string(), }); const querySchema = z.object({ search: z.string().optional(), }); const bodySchema = z.object({ field: z.string(), }); export const GET = createSafeRoute() .params(paramsSchema) .query(querySchema) .body(bodySchema) .handler((request, context) => { const { id } = context.params; const { search } = context.query; const { field } = context.body; return Response.json({ id, search, field }), { status: 200 }; });
To define a route handler in Next.js:
createSafeRoute and your validation library (e.g., zod).createSafeRoute() to create a route handler, chaining params, query, and body methods.context.Tests are written using Vitest. To run the tests, use the following command:
pnpm testContributions are welcome! For major changes, please open an issue first to discuss what you would like to change.
This project is licensed under the MIT License - see the LICENSE file for details.