honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.65k stars 524 forks source link

why you can only add Middlewares to the root hono app #3358

Open lord007tn opened 2 weeks ago

lord007tn commented 2 weeks ago

What version of Hono are you using?

4.5.10

What runtime/platform is your app running on?

Nodejs

What steps can reproduce the bug?

// authors.ts

import { Hono } from 'hono'
import { authMiddleware } from '@/middlewares/auth';

const app = new Hono()
  .get('/', (c) => c.json('list authors'))
  .post('/', (c) => c.json('create an author', 201))
  .get('/:id', (c) => c.json(`get ${c.req.param('id')}`))

// block unauthenticated requests to all routes inside this file: not working
app.use('/*', authMiddleware )

export default app

// books.ts

import { Hono } from 'hono'

const app = new Hono()
  .get('/', (c) => c.json('list books'))
  .post('/', (c) => c.json('create a book', 201))
  .get('/:id', (c) => c.json(`get ${c.req.param('id')}`))

export default app

// index.ts

import { Hono } from 'hono'
import authors from './authors'
import books from './books'
import { authMiddleware } from '@/middlewares/auth';

const app = new Hono()

// block unauthenticated requests to all author routes: working
app.use('/authors/*', authMiddleware )

const routes = app.route('/authors', authors).route('/books', books)

export default app
export type AppType = typeof routes

so if you attempt to add authMiddleware to the child hono app it wont work

What is the expected behavior?

i think for better developer experience we should have the ability to add middlewares and encapsulate them inside children hono apps

What do you see instead?

middlewares only works if you add it to the root app and have it point to the absolute path

Additional information

No response

MathurAditya724 commented 2 weeks ago

You can also wrote it like this to achieve what you want

// author.ts
import { Hono } from 'hono'
import { authMiddleware } from '@/middlewares/auth';

const app = new Hono().use(authMiddleware)

app.get('/', (c) => c.json('list authors'))

app.post('/', (c) => c.json('create an author', 201))
  .get('/:id', (c) => c.json(`get ${c.req.param('id')}`))

export default app

Instead of doing app.use('/*', authMiddleware), you can do app.use(authMiddleware) and place all the middleware before defining the routes

lord007tn commented 2 weeks ago

docs should state that middlewares should be used before the route declaration

MathurAditya724 commented 2 weeks ago

Is this what you are looking for? - https://hono.dev/docs/guides/middleware#definition-of-middleware

lord007tn commented 2 weeks ago

@MathurAditya724 i read the whole docs no mention that middleware should be used before the route and for this it should be said somewhere