The Next.js middleware is a somewhat unpopular part of the framework. The top search result for next.js middleware reddit yields:
Let's try to find out if the animosity is justified and answer the question: Should you use next.js middleware?
If you deploy a next.js application with Vercel, the middleware will be executed on Cloudflare's workers network in the region closest to the request. Cloudflare workers currently run in over 200 regions. In order to launch the worker as quickly as possible, Cloudflare deploys a custom runtime which is a subset of the node runtime.
While this minimalistic runtime decreases cold start times and can lead to very fast response times, it is also one reason for developer dissatisfaction. Due to its reduced functionality many popular npm packages cannot be used in the workers environment.
If you are working with database sessions (which you most likely should) and you want to offer a good user experience you have to update the expiration of the session every time the user is interacting with your application. Otherwise the user would get logged out suddenly and unexpectedly at some point.
This bears the question: How to refresh a database session in a Next.js application in a way that affects the performance of your application the least?
Since you will refresh the session on every user action, it's worthwhile to find a way that has the smallest possible performance impact.
In this article we want to explore three possible options:
\