Add Middleware Folder Support to Next.js #74851
FaryarKankash
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Goals
Non-Goals
No response
Background
For many years, I have developed frontend applications using Vue and React. While working with Nuxt.js, I was impressed by its middleware folder feature, which allows developers to create various middleware files, such as is-login.ts, is-admin.ts, and more. These middleware functions can then be easily applied to specific pages using a simple syntax like middleware: [isLogin, isAdmin]. Nuxt.js automatically ensures that all specified middleware are executed for the given page.
In contrast, Next.js currently relies on the middleware.ts file with pathname matching, which can feel less intuitive and more cumbersome for developers managing multiple middlewares. I believe adopting a similar middleware folder approach would not only simplify the process but also significantly enhance the developer experience (DX) for this already amazing project. 🙏
Proposal
This feature could be implemented by introducing a middleware folder, similar to Nuxt.js, where developers can store various middleware files (e.g., isLogin.ts, isAdmin.ts, etc.). The middleware could then be assigned to specific pages in a straightforward manner using a middleware array in the page's configuration. This would allow Next.js to automatically check and run the assigned middleware without requiring complex pathname matches.
Additionally, in the Next.js App Router, we could leverage a syntax like:
export const middleware = [isLogin, isAdmin, ...];
This would allow developers to easily export an array of middleware for a specific page or group of pages, providing better reusability and cleaner code. This syntax is simple, clear, and intuitive, allowing for middleware logic to be applied directly to pages with minimal effort.
For implementation, the Next.js team could add functionality where the middleware folder is automatically recognized by the framework, and any middleware defined inside it could be easily referenced on a page-by-page basis. This approach would maintain the existing flexibility of Next.js, while streamlining middleware management and improving the developer experience.
Beta Was this translation helpful? Give feedback.
All reactions