hono icon indicating copy to clipboard operation
hono copied to clipboard

Redirects not occuring when triggered from middleware

Open GibzClt opened this issue 3 months ago • 1 comments

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
Image

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

Image

GibzClt avatar Nov 21 '25 10:11 GibzClt

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')
  })
}

yusukebe avatar Dec 11 '25 08:12 yusukebe

This issue has been marked as stale due to inactivity.

github-actions[bot] avatar Dec 19 '25 00:12 github-actions[bot]