Redirects not occuring when triggered from middleware
What version of Hono are you using?
4.10.2
What runtime/platform is your app running on? (with version if possible)
Node v22
What steps can reproduce the bug?
To reproduce the bug, I used hono playground available at https://playground.hono.dev/
Minimal code required
import { Hono } from 'https://esm.sh/hono'
import { createMiddleware } from 'https://esm.sh/hono/factory';
const app = new Hono()
function redirectMid() {
return createMiddleware(async (c, next) => {
console.log('Before handler');
await next();
if (c.error) {
console.log('hit error');
return c.redirect('/foo');
}
console.log('no error, no redirect');
})
}
app.get('/hello', redirectMid(), (c) => {
const name = c.req.query('name')
if (name === 'error') {
throw new Error();
}
return c.text(`Hello ${name}!`)
})
app.get('/foo', (c) => {
return c.text('Foo response');
})
export default app
Now in the playground hit /hello?name=error
What is the expected behavior?
The expected behaviour is for the app to redirect to /foo with the following order
log> Before handler
log> hit error
res> Foo response
What do you see instead?
Instead what I see is
log> Before handler
res> Internal Server Error
log> hit error
log> no error, no redirect
Video snippet https://github.com/user-attachments/assets/606b3aa1-c7ce-4f97-bebd-ada43364c8fe
Additional information
I tried wrapping the await next() with a try-catch block but it didn't catch any error which I think resonated with what is mentioned in the docs
Hi @GibzClt
To change the response after next, can you use this syntax? It's documented here: https://hono.dev/docs/guides/middleware#modify-the-response-after-next
function redirectMid() {
return createMiddleware(async (c, next) => {
console.log('Before handler')
await next()
if (c.error) {
console.log('hit error')
c.res = c.redirect('/foo') // change this line
}
console.log('no error, no redirect')
})
}
This issue has been marked as stale due to inactivity.