██████╗ ██╗ ██╗██╗███╗ ██╗ ██████╗ ███████╗ ██╔══██╗██║ ██║██║████╗ ██║██╔════╝ ██╔════╝ ██║ ██║██║ ██║██║██╔██╗ ██║██║ ███╗█████╗ ██║ ██║╚██╗ ██╔╝██║██║╚██╗██║██║ ██║██╔══╝ ██████╔╝ ╚████╔╝ ██║██║ ╚████║╚██████╔╝███████╗ ╚═════╝ ╚═══╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝

DVINGE_BLOG.SYS

HEAD OF CLOUD :: DEVOPS EXPERT :: TECH ENTHUSIAST
:: CLOUD ARCHITECT :: PROBLEM SOLVER :: FATHER OF 3 :: HOMELAB BUILDER :: SCALING THE NEXT UNICORN @ SCALEUP FINANCE :: DIY AUTOMATION NERD :: TECH PASSIONATE :: CONTINUOUS LEARNER ::

Supercharging NextJS with Chainable Middlewares 🔗

When I recently built a NextJS application, I ran into a classic problem - my middleware.ts file was getting out of hand. NextJS’s middleware feature is powerful, but as I needed to add more functionality like authentication, logging, and request tracking, my code started to become messy and hard to test.

The Challenge with NextJS Middleware

The default way of handling middleware in NextJS is through a single middleware.ts file in your project root. It’s great for simple cases, but as your needs grow, you might end up with something like this: