clientIp property

String? get clientIp

The originating client address.

Returns ip unless TRUSTED_PROXIES names the peer, in which case the left-most entry of X-Forwarded-For is returned instead.

X-Forwarded-For is trivially spoofed by the client, so it is only consulted when the request actually came from a proxy you listed. TRUSTED_PROXIES is a comma-separated list of addresses; the value * trusts any peer and should only be used when something else guarantees the app is unreachable except through the proxy.

Implementation

String? get clientIp {
  final peer = ip;
  if (peer == null) return null;

  final trusted = env<String>(
    'TRUSTED_PROXIES',
    '',
  ).split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
  if (trusted.isEmpty) return peer;
  if (!trusted.contains('*') && !trusted.contains(peer)) return peer;

  final forwarded = header('x-forwarded-for');
  if (forwarded == null || forwarded.isEmpty) return peer;

  final first = forwarded.split(',').first.trim();
  return first.isEmpty ? peer : first;
}