Should you use Next.js middleware?

The middleware is a somewhat frowned upon part of the Next.js framework. The top Google search result for next.js middleware reddit is currently:

Anyone else hate NextJS middleware implementation?

😅

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:

  1. In the Next.js middleware
  2. In the Next.js Page component which is a react server component
  3. In a react client component


\

Middleware