Any way to modify the request path in middleware? #2642
-
I am trying to replicate a legacy API which had optional versions in paths, so I was hoping to add some middleware that just intercepted paths starting with Is this possible? I've seen examples that clone Any suggestions? (for added complexity we are using the zod-openapi middleware so I can't just give our routes both |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
How about using import { Hono } from 'hono'
const app = new Hono()
app.get('/api/hello', (c) => {
return c.text('api')
})
app.use('/api/v1/*', async (c) => {
const newPath = c.req.path.replace(/^\/api\/v1/, '/api');
// 301 means redirect-permanently
return c.redirect(newPath)
}) This avoids setting up legacy APIs one at a time. |
Beta Was this translation helpful? Give feedback.
sadly that only works if our external clients all respect
301 redirect
and I'm not totally confident they do.What we decided on was to move to hono v4 and just specify multiple paths. (and we ditched the hod-zono-openapi stuff so we can hide the
/v1
from our schema)Our resulting code:
Not as generic as a middleware for all routes - but a lot less work.