set method

void set(
  1. String name,
  2. String value, {
  3. String? domain,
  4. String? path = '/',
  5. DateTime? expires,
  6. Duration? maxAge,
  7. bool httpOnly = true,
  8. bool secure = true,
  9. String? sameSite = 'lax',
})

Sets a cookie in the response.

Implementation

void set(
  String name,
  String value, {
  String? domain,
  String? path = '/',
  DateTime? expires,
  Duration? maxAge,
  bool httpOnly = true,
  bool secure = true,
  String? sameSite = 'lax',
}) {
  if (_response == null) return;

  if (name.isEmpty || !_cookieNamePattern.hasMatch(name)) {
    throw ArgumentError('Invalid cookie name: $name');
  }

  if (value.contains('\r') ||
      value.contains('\n') ||
      value.contains('\x00')) {
    throw ArgumentError('Invalid cookie value');
  }

  final normalizedSameSite = sameSite?.toLowerCase();
  if (normalizedSameSite == 'none' && !secure) {
    throw ArgumentError('SameSite=None requires secure=true');
  }

  final cookie = Cookie(name, value);

  if (domain != null) cookie.domain = domain;
  if (path != null) cookie.path = path;
  if (expires != null) cookie.expires = expires;
  if (maxAge != null) cookie.maxAge = maxAge.inSeconds;
  cookie.httpOnly = httpOnly;
  cookie.secure = secure;

  if (normalizedSameSite != null) {
    switch (normalizedSameSite) {
      case 'strict':
        cookie.sameSite = SameSite.strict;
        break;
      case 'lax':
        cookie.sameSite = SameSite.lax;
        break;
      case 'none':
        cookie.sameSite = SameSite.none;
        break;
      default:
        throw ArgumentError('Invalid SameSite value: $sameSite');
    }
  }

  _response.cookies.add(cookie);
}