Replies: 2 comments
|
What type of route configuration? Setting and getting values between routes per request, or something more specific? |
|
Hono doesn't have a route-config API like that: there's no third metadata argument on route definitions and nothing like Pattern 1: a small middleware factory that closes over the config (closest to your snippet) import { createMiddleware } from 'hono/factory'
type Env = { Variables: { config: { auth?: boolean } } }
const withConfig = (config: Env['Variables']['config']) =>
createMiddleware<Env>(async (c, next) => {
c.set('config', config)
await next()
})
// scope it to a path...
app.use('/user/*', withConfig({ auth: true }))
// ...or attach it per route, before the handler
app.get('/user/profile', withConfig({ auth: true }), (c) => {
const config = c.get('config')
// ...
})Any middleware or handler that runs after it reads the value with Pattern 2: one global middleware + a config map keyed by route pattern If the config is naturally a table (one entry per route), keep a map and look it up by the matched route pattern, which Hono exposes as const routeConfig: Record<string, { auth?: boolean }> = {
'/user/:id': { auth: true },
'/post/:id': { auth: false },
}
app.use(async (c, next) => {
c.set('config', routeConfig[c.req.routePath] ?? {})
await next()
})Keying by Pattern 1 is the better default, the config sits next to the routes it applies to and there's no table to keep in sync. Pattern 2 earns its keep when config is generated or loaded from somewhere else (a database, a config file) rather than written inline. |
Uh oh!
There was an error while loading. Please reload this page.
like this
All reactions