Simplify your Next.js Middleware

Z4NR34L
Rescale
Published in
2 min readJan 7, 2024
Next.js Middleware missing polyfill for multiple or complex middlewares

Motivation

I’m working with Next.js project for a few years now, after Vercel moved multiple /**/_middleware.ts files to a single /middleware.ts file, there was a unfilled gap - but just for now. After a 2023 retro I had found that there is no good solution for that problem, so I took matters into my own hands. I wanted to share that motivation with everyone here, as I think that we all need to remember how it all started.

Hope it will save you some time and would make your project DX better!

The problem

By default Next.js supports only one middleware.ts file, in which you need match routes with logic by your own which can be pretty problematic and chaotic. Also it’s endlessly making middleware boilerplate bigger.

This exmaple is not that scary, but imagine adding more complex logic for few more routes… (ugh)

The solution

Let me introduce to you my latest package called next-easy-middleware.

Installation:

pnpm add next-easy-middleware / npm install next-easy-middleware / bun add next-easy-middleware

Usage:

Feedback

I’m awaiting your feedback about that solution, also feelfree to contribute to that package in below repository.

Enjoy!

--

--

Z4NR34L
Rescale
Editor for

IT professional since 2007, self-taught programmer turned cybersecurity expert & software engineer, passionate about interdisciplinary knowledge.