Overview
Ship provides two essential middleware utilities for API routes:- Rate Limit Middleware — protects your API endpoints from excessive requests
- Validate Middleware — validates incoming request data using Zod schemas
/api/src/middlewares
and can be imported and applied to any route.
Rate Limit Middleware
The rate limit middleware protects your API endpoints from abuse by limiting the number of requests a user can make within a specified time window. It automatically uses Redis when available, falling back to in-memory storage for development environments.Parameters
TherateLimitMiddleware
function accepts an options object with the following parameters:
limitDuration
(optional) — Time window in seconds. Default:60
secondsrequestsPerDuration
(optional) — Maximum number of requests allowed within the time window. Default:10
errorMessage
(optional) — Custom error message shown when rate limit is exceeded. Default:'Looks like you are moving too fast. Retry again in few minutes.'
Key Features
- Automatic Storage Selection: Uses Redis if
REDIS_URI
is configured, otherwise falls back to in-memory storage - User-Specific Limits: Rate limits are applied per authenticated user (based on
user._id
) or per IP address for unauthenticated requests - Response Headers: Includes rate limit headers in the response for client-side tracking
Example
Common Use Cases
- Protecting email sending endpoints
- Rate limiting authentication attempts
- Preventing API abuse on expensive operations
- Throttling public API endpoints
Validate Middleware
The validate middleware automatically validates incoming request data against a Zod schema. It combines data from request body, files, query parameters, and route parameters into a single validated object.How It Works
The middleware validates the following request data:- Request body (
ctx.request.body
) - Uploaded files (
ctx.request.files
) - Query parameters (
ctx.query
) - Route parameters (
ctx.params
)
400
error with detailed field-level error messages. If validation succeeds, the validated data is available via ctx.validatedData
.