Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

middleware next() return type is inaccurate #2421

Open
thiskevinwang opened this issue Mar 26, 2024 · 2 comments
Open

middleware next() return type is inaccurate #2421

thiskevinwang opened this issue Mar 26, 2024 · 2 comments
Labels

Comments

@thiskevinwang
Copy link

What version of Hono are you using?

4.1.4

What runtime/platform is your app running on?

Cloudflare workers

What steps can reproduce the bug?

Use a bare bones middleware, and log in the middleware

import { Hono } from 'hono';

const app = new Hono()

app.use(async (ctx, next) => {
  // typed as void, but actual value is a Context object.
  const nextResult = await next();
  console.log('nextResult', nextResult);
});

What is the expected behavior?

I expect the result of await next() to be undefined, since the return type is void.

What do you see instead?

I see the actual value as a full Hono Context object.

Additional information

  • Also tested on Hono 4.0.1.
  • 💭 The returned Context object enables a lot of additional use cases. ie. checking ctx.error for if a wrapped middleware threw. Otherwise, middlewares are unable to detect if any wrapped middleware has thrown, since await next() does not appear to ever throw.
@yusukebe
Copy link
Member

@thiskevinwang Thanks! I'll handle this matter later.

@yusukebe
Copy link
Member

This matter should be considered.

Exactly, the return value from await next() is Context, so it's better to type it. But, only by changing, another type error will occur if return next() in a middleware:

app.use(async (c, next) => {
  return next()
})
Screenshot 2024-03-30 at 7 35 05

This error disappears if make void to unknown:

// type MiddlewareHandler = (c: Context, next: Next) => Promise<Response | void>
type MiddlewareHandler = (c: Context, next: Next) => Promise<Response | unknown> // <===

But, if so, a user may return unexpected values in the middleware:

app.use(async (c, next) => {
  return 'something'
})

We should avoid it because this will cause runtime errors. Ideally, after doing await next(), it should be allowed to return unknown, but this seems difficult.

And we can handle the Context object like this. Is not enough?

app.use(async (c, next) => {
  await next()
  if (c.error) {
    console.log('error', c.error.name)
  }
})

@yusukebe yusukebe added triage and removed bug labels Sep 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants