HonoH
Hono4mo ago
Zachary

Many JWT Middlewares OR-ed together

Hi, I have a set of legal JWT keys. I'd like any one of them to allow a request through the middleware.

This works:
export default function orCombinator<
  E extends HonoEnv = any,
  P extends string = string,
  I extends Input = {},
>(
  handlers: Array<MiddlewareHandler<E, P, I>>,
  onFail: (c: Context<E, P, I>) => Response,
): (c: Context<E, P, I>, next: Next) => Promise<Response | void> {
  return async (c, next) => {
    if (handlers.length == 0) {
      return onFail(c);
    } else {
      const handler = handlers[0];
      try {
        return await handler(c, next);
      } catch {
        return orCombinator(handlers.slice(1), onFail)(c, next);
      }
    }
  };
}

...
orCombinator([jwt({secret: "bizfoobar"}), jwt({secret: "foobarbaz"})], c => c.text("no can do"))


Is there a supported mechanism for this?
Was this page helpful?