except function
Skips middleware (calls next() directly) whenever condition matches
the current request; otherwise runs middleware normally.
condition can be:
- A
Stringpath pattern, where*acts as a wildcard (e.g./api/public/*). - A
Listof path patterns and/orbool 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);
};
}