handle method

  1. @override
Future<void> handle(
  1. Request req
)
override

Inspect or reject the request. Throw to abort the chain.

The default implementation does nothing, so a middleware that only overrides process does not need to define it.

Implementation

@override
Future<void> handle(Request req) async {
  final headers = req.response.headers;

  // A null/empty value *removes* the header rather than skipping it.
  // Dart pre-populates several of these, so "not configured" has to
  // mean "not present" — otherwise there would be no way to drop a
  // default this middleware disagrees with.
  void set(String name, String? value) {
    if (value == null || value.isEmpty) {
      headers.removeAll(name);
      return;
    }
    headers.set(name, value);
  }

  set('X-Content-Type-Options', contentTypeOptions);
  set('X-Frame-Options', frameOptions);
  set('Referrer-Policy', referrerPolicy);
  set('Content-Security-Policy', contentSecurityPolicy);
  set('Permissions-Policy', permissionsPolicy);
  set('X-XSS-Protection', xssProtection);

  if (_isSecure(req)) {
    set(
      'Strict-Transport-Security',
      strictTransportSecurity ?? 'max-age=31536000; includeSubDomains',
    );
  }

  if (removeServerHeader) {
    headers.removeAll(HttpHeaders.serverHeader);
  }
}