next-safe-route
v0.0.20
Published
A safer way to define route handlers in Next.js
Downloads
86
Maintainers
Readme
next-safe-route
is a utility library for Next.js that provides type-safety and schema validation for Route Handlers/API Routes.
Features
- ✅ Schema Validation: Automatically validate request parameters, query strings, and body content with built-in error handling.
- 🧷 Type-Safe: Work with full TypeScript type safety for parameters, query strings, and body content.
- 😌 Easy to Use: Simple and intuitive API that makes defining route handlers a breeze.
- 🔗 Extensible: Compatible with any validation library supported by TypeSchema.
- 🧪 Fully Tested: Extensive test suite to ensure everything works reliably.
Installation
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.
Usage
// 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:
- Import
createSafeRoute
and your validation library (e.g.,zod
). - Define validation schemas for params, query, and body as needed.
- Use
createSafeRoute()
to create a route handler, chainingparams
,query
, andbody
methods. - Implement your handler function, accessing validated and type-safe params, query, and body through
context
.
Tests
Tests are written using Vitest. To run the tests, use the following command:
pnpm test
Contributing
Contributions are welcome! For major changes, please open an issue first to discuss what you would like to change.
License
This project is licensed under the MIT License - see the LICENSE file for details.