About Middleware
Reusable Fastify middleware and hooks
Browse the snippets below to find the middleware implementation you need for your Fastify project.
All Middleware Snippets
JWT Authentication
JWT middleware with role-based access control
- JWT verification via @fastify/jwt
- Role-based access control
- Token generation helpers
API Key Authentication
API key auth for service-to-service communication
- Header-based API key
- Multiple key support
- Timing-safe validation
CORS Configuration
Cross-origin resource sharing with environment config
- Environment variable configuration
- Origin whitelist support
- Credentials handling
Helmet Security
Security headers via @fastify/helmet
- Content Security Policy
- HSTS with preload
- XSS protection
Rate Limiter
Rate limiting with @fastify/rate-limit
- Configurable limits
- Route-specific rate limits
- Presets for common use cases
Pino Logger
Structured logging with Pino
- Multiple log levels
- Sensitive field redaction
- Pretty print in development
Zod Validation
Request validation with Zod schemas
- Body validation
- Query and params validation
- Type inference
Error Handler
Global error handling with custom error classes
- Global error catching
- Custom error classes
- Environment-aware responses
How to Use
Install any snippet using the Hanma CLI:
npx hanma add --framework fastify
For example, to install the first snippet:
npx hanma add fastify-jwt --framework fastify