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 (shared context) 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.
Waring! Keep this as fast as possible, as longer the middleware executes the longer the TTFB will be.