except function

Middleware except(
  1. Object condition,
  2. Middleware middleware
)

Skips middleware (calls next() directly) whenever condition matches the current request; otherwise runs middleware normally.

condition can be:

  • A String path pattern, where * acts as a wildcard (e.g. /api/public/*).
  • A List of path patterns and/or bool Function(Context) predicates (the middleware is skipped when any element matches — OR logic).
  • A bool Function(Context c) predicate.
// Skip auth for public routes:
app.mount('/api/*', except(
  '/api/public/*',
  bearerAuth(token: token),
));

// Multiple exclusions:
app.use(except(
  ['/health', '/api/public/*'],
  bearerAuth(token: token),
));

// Custom predicate:
app.use(except(
  (c) => c.req.method == 'OPTIONS',
  bearerAuth(token: token),
));

Implementation

Middleware except(Object condition, Middleware middleware) {
  final check = _buildCheck(condition);

  return (Context c, Next next) async {
    if (check(c)) {
      await next();
      return;
    }
    await middleware(c, next);
  };
}