optionalJwt function

Middleware optionalJwt({
  1. required String secret,
  2. String alg = 'HS256',
  3. String? cookie,
  4. String headerName = 'authorization',
  5. VerifyOptions? verifyOptions,
})

Optional JWT middleware — never rejects the request.

If a valid Bearer token is present, stores the payload in c.get('jwtPayload') and c.user. Useful for routes that are public but show extra content when the user is authenticated.

app.mount('/feed', optionalJwt(secret: env.secret));

app.get('/feed', (c) {
  final user = c.user; // null for anonymous, Map for authenticated
  return c.ok({'personalised': user != null});
});

Implementation

Middleware optionalJwt({
  required String secret,
  String alg = 'HS256',
  String? cookie,
  String headerName = 'authorization',
  VerifyOptions? verifyOptions,
}) {
  return (Context c, Next next) async {
    String? token;

    if (cookie != null) {
      token = _parseCookie(c.req.header('cookie'), cookie);
    } else {
      final raw = c.req.header(headerName);
      if (raw != null && raw.startsWith('Bearer ')) {
        token = raw.substring(7).trim();
      }
    }

    if (token != null && token.isNotEmpty) {
      final payload = _verifyJwt(token, secret, alg: alg, options: verifyOptions);
      if (payload != null) {
        c.set('jwtPayload', payload);
        c.user = payload;
      }
    }

    await next();
  };
}