honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.68k stars 527 forks source link

Support for Express.js Compatible Middleware #3293

Open dipakparmar opened 1 month ago

dipakparmar commented 1 month ago

I'm exploring the possibility of supporting Express.js compatible middleware in Hono. This would allow for easier migration from Express to Hono and enable the use of the vast ecosystem of Express middleware within Hono applications.

Proposed Implementation

I'm looking for something like this for backward compatibility:

type ExpressMiddleware = (
  req: IncomingMessage,
  res: ServerResponse,
  next: (err?: any) => void
) => void

export function adaptExpressMiddleware(middleware: ExpressMiddleware): MiddlewareHandler {
  return async (c: Context, next: Next) => {
    const req = c.req.raw as unknown as IncomingMessage
    const res = c.res as unknown as ServerResponse

    await new Promise<void>((resolve, reject) => {
      middleware(req, res, (err) => {
        if (err) reject(err)
        else resolve()
      })
    })

    await next()
  }
}

const app = new Hono()
app.use(adaptExpressMiddleware(existingexpressmiddleware()));

Current Issues

So far, I haven't been able to make this work due to type incompatibility issues. The main challenges are:

  1. Hono's Context object doesn't directly map to Express's req and res objects.
  2. The IncomingMessage and ServerResponse types from Node.js http module don't align perfectly with Hono's request and response handling.

Questions

  1. Is it feasible to implement such an adapter in Hono?
  2. What would be the best approach to handle the type mismatches between Express and Hono?
  3. Are there any performance implications we should consider when adapting Express middleware?

Goals

Any insights, suggestions, or assistance on how to achieve this would be greatly appreciated. Thank you!

yusukebe commented 1 month ago

Hi @dipakparmar

This is a super exciting proposal, though I don't know if we should do it in our official repo like honojs/middleware or hono/node-server. I think it is more prefer discussing it in the honojs/hono repo. So I'll transfer it.

yusukebe commented 1 month ago

A quick response.

I think we can also follow the Connect specs: https://github.com/senchalabs/connect

dipakparmar commented 1 month ago

A quick response.

I think we can also follow the Connect specs: senchalabs/connect

Thanks @yusukebe, https://github.com/senchalabs/connect looks interesting, I'll check it out.