honojs / node-server

Node.js Server for Hono
https://hono.dev
307 stars 41 forks source link

How to deal with `ERR_HTTP_HEADERS_SENT` errors? #152

Closed tlaziuk closed 3 months ago

tlaziuk commented 3 months ago

Hey, I have an application that has been using express and I'd like to replace it with hono, but in the development mode the app is using 3 express middlewares (webpack-dev-middleware, webpack-hot-middleware and connect-history-api-fallback) that I can not simply "drop".

The thing is each time I allow the hono middleware to resolve the ERR_HTTP_HEADERS_SENT error is being thrown. The only solution that I've figured is to leak memory by not resolving the middleware:

  app.use(
    async (c, next) => {
      try {
        const { resolve, reject, promise: deferred } = defer<void>()

        const {
          incoming,
          outgoing,
        } = c.env

        outgoing.once('finish', reject)

        await devMiddleware(
          incoming,
          outgoing,
          resolve,
        )

        await deferred

        // `deferred` is resolved, it means `next` has been called in the express middleware, so hono's next can also be called
        await next()
      } catch (error) {
        // request has been handled by the express middleware, how to signal that to hono?

        // this will never resolve, ergo the request will never be full handled by hono, but that's a memory leak
        return new Promise<void>(() => {})
      }
    },
  )

As you may suspect doing so is not the most optimal solution. But is there another, recommended way of handling express/connect middlewares?

tlaziuk commented 3 months ago

I think this is a wrong place for asking questions, I've started a discussion here https://github.com/orgs/honojs/discussions/2377