Next.js Middleware: Express.js Simplicity vs. Next.js Complexity? Seeking Best Practices
Unanswered
Schneider’s Smooth-fronted Caima… posted this in #help-forum
Schneider’s Smooth-fronted CaimanOP
Hi everyone, I'm transitioning from MERN stack development (Express.js) to Next.js. In Express.js, defining and applying middleware was incredibly intuitive. I'd have separate middleware functions (e.g., authentication, authorization) and simply chain them in the desired order for specific routes:
However, Next.js middleware seems quite different. From what I've gathered, all middleware goes into a single middleware.ts file, requiring conditional checks for routes and methods. To chain middleware, recursion seems necessary. For large projects, this approach feels cumbersome and less maintainable.
Am I missing something? Is there a cleaner way to organize and apply Next.js middleware that aligns more closely with the Express.js approach? I'm hoping to find best practices or patterns that simplify middleware management in Next.js.
Thanks in advance for any insights or advice!
// Express.js example
router.get("/:id/edit", isLoggedIn, isAuthor, catchAsync(campgrounds.renderEditForm));However, Next.js middleware seems quite different. From what I've gathered, all middleware goes into a single middleware.ts file, requiring conditional checks for routes and methods. To chain middleware, recursion seems necessary. For large projects, this approach feels cumbersome and less maintainable.
Am I missing something? Is there a cleaner way to organize and apply Next.js middleware that aligns more closely with the Express.js approach? I'm hoping to find best practices or patterns that simplify middleware management in Next.js.
Thanks in advance for any insights or advice!
4 Replies
The official guide is the best one to follow
Schneider’s Smooth-fronted CaimanOP
Thank you very much for replying, and I have went through that, however I am asking for something little more which is there in the post.
@Schneider’s Smooth-fronted Caiman from my experience, I had to create different middlewares in HOF pattern and apply them in route handlers not using global middleware.
In app router, middleware currently is on edge runtime which means you can use libraries based on web apis [https://nextjs.org/docs/app/api-reference/edge].
So my idea is to use next.js middleware to apply middleware logic which should be all/most of your api routes. and then for specific middleware logic for different api routes, you would need to make your middlewares
In app router, middleware currently is on edge runtime which means you can use libraries based on web apis [https://nextjs.org/docs/app/api-reference/edge].
So my idea is to use next.js middleware to apply middleware logic which should be all/most of your api routes. and then for specific middleware logic for different api routes, you would need to make your middlewares