next-api-shield
v1.0.0
Published
One-line middleware for Next.js API routes with rate limiting, validation, and more.
Maintainers
Readme
next-api-shield
A lightweight middleware for Next.js API routes that provides rate limiting, input validation, standardized error formatting, and CORS handling with full TypeScript support.
Installation
Install the package and its peer dependency, zod:
npm install next-api-shield zodAlternatively, using other package managers:
pnpm add next-api-shield zodyarn add next-api-shield zodbun add next-api-shield zodFeatures
- Rate Limiting: Prevent abuse with in-memory request tracking.
- Input Validation: Type-safe request body and query validation using Zod.
- CORS Support: Easily manage allowed origins and methods.
- Standardized Errors: Consistent JSON error responses for validation and rate limits.
- Request Logging: Optional logging for incoming API requests.
Usage
Wrap your Next.js API handler with the shield function.
import { shield } from "next-api-shield";
import { z } from "zod";
const userSchema = z.object({
email: z.string().email(),
name: z.string().min(2),
});
const handler = async (req, res) => {
res.status(200).json({ message: "User created successfully" });
};
export default shield(handler, {
validate: {
body: userSchema,
},
rateLimit: {
max: 10,
windowMs: 60000, // 1 minute
},
cors: {
origin: "https://yourdomain.com",
methods: ["POST"],
},
log: true,
});Configuration Options
The shield function accepts a configuration object with the following optional properties:
| Property | Type | Description |
| ----------- | ------- | ----------------------------------------------------- |
| validate | object | Contains Zod schemas for body and query. |
| rateLimit | object | Define max requests and windowMs timeframe. |
| cors | object | Define origin (string/array) and methods (array). |
| log | boolean | Enables console logging for every request. |
Error Responses
When a check fails, the middleware returns a standardized response:
- Validation Error: Status
400 - Rate Limit Exceeded: Status
429 - Internal Server Error: Status
500
