honojs / honox

HonoX - Hono based meta framework
https://hono.dev
MIT License
1.4k stars 38 forks source link

Add `_middleware.ts` file #64

Closed bruceharrison1984 closed 7 months ago

bruceharrison1984 commented 7 months ago

What is the feature you are proposing?

Would it be possible to create a _middleware.ts file that would automatically add the middleware to routes at and below it? Cumulative _middleware declarations would be merged, with higher ones taking precedence in the ordering.

//_middleware.ts
import { someMiddleware } from '../middleware/someMiddleware'
import { someOtherMiddleware } from '../middleware/someOtherMiddleware'

// middleware would be ran in the order declared here
exports default [ someMiddleware, someOtherMiddleware ]

This would make it unnecessary to have to redeclare the middleware pipeline for each route, or manually create a Hono router just to gain access to the use method.

Directory structure would look like:

.
└── app/
    └── routes/
        ├── some-path/
        │   ├── uses-middleware/
        │   │   └── index.ts    <--uses _middleware
        │   ├── _middleware.ts
        │   └── index.ts        <--uses _middleware
        └── index.ts
yusukebe commented 7 months ago

Thanks @bruceharrison1984 !

It's very interesting! The API in which it can export Middleware[] as default seems to be good. I'll consider implementing this and replay it later.

bruceharrison1984 commented 7 months ago

@yusukebe I threw this together this morning: https://github.com/honojs/honox/pull/67

The work done for _renderer.tsx did most of the hard work, this was relatively simple based on that!