Best practices
Best practices for developing Next.js middleware
Performance
Middleware performance is critical to the overall performance of your application. Whole middleware execution time should be as low as possible as it's executed before every request - which means it's directly affecting TTFB (Time To First Byte) of your application.
Concurrency
Minimize the number of blocking operations in your middleware. If you need to perform blocking operations, consider using concurrency to parallelize the operations.
Caching
Caching is a powerful technique to improve the performance of your middleware and reduce heavy operations like db queries. There are two types of caching you can use:
Cross-middleware caching
Use build-in storage to cache data that is used across multiple middleware functions in a chain.
This will reduce the number of requests to external services and reduce middleware exeuction time.
Cross-requests caching
Build a custom adapter to cache data between requests using for example redis, Vercel Edge Config or other KV storage.
Warning! Keep this as fast as possible, as longer the middleware executes the longer the TTFB will be.
Security
Rate limiting
Implement rate limiting in your middleware to protect your application from abuse and potential DoS attacks. Rate limiting can be applied globally or to specific routes.
Authentication
Implement authentication checks early in your middleware chain to protect routes. Use storage to avoid redundant authentication checks in subsequent middleware functions.
Authorization
Run authorization checks in middleware to control access to protected resources based on user roles and permissions.
Reliability
Monitoring
NEMO provides built-in performance monitoring that you can easily enable through configuration options:
When enableTiming
is enabled, NEMO will automatically:
- Track execution time for each middleware function
- Measure performance across different middleware chains (before, main, after)
- Log detailed timing information in the console
Logging
Implement structured logging in your middleware for better debugging and traceability.
Testing
Write comprehensive tests for your middleware to ensure reliability and catch regressions.