referrerPolicy function

Middleware referrerPolicy({
  1. List<ReferrerPolicyToken> policies = const [ReferrerPolicyToken.noReferrer],
})

The Referer HTTP header is typically set by web browsers to tell the server where it's coming from. For example, if you click a link on example.com/index.html that takes you to wikipedia.org, Wikipedia's servers will see Referer: example.com. This can have privacy implications—websites can see where you are coming from. The new Referrer-Policy HTTP header lets authors control how browsers set the Referer header.

Read the spec to see the options you can provide.

Usage:

import 'package:shelf_helmet/shelf_helmet.dart';

.addMiddleware(referrerPolicy(policies: [ReferrerPolicyToken.sameOrigin])) -> Referrer-Policy: same-origin

.addMiddleware(referrerPolicy(policies: [ReferrerPolicyToken.unsafeUrl])) -> Referrer-Policy: unsafe-url

.addMiddleware(referrerPolicy(policies: [ReferrerPolicyToken.noReferrer, ReferrerPolicyToken.unsafeUrl])) -> Referrer-Policy: no-referrer,unsafe-url

.addMiddleware(referrerPolicy()) -> Referrer-Policy: no-referrer

Implementation

Middleware referrerPolicy({
  List<ReferrerPolicyToken> policies = const [
    ReferrerPolicyToken.noReferrer,
  ],
}) {
  final args = [
    for (final policy in policies)
      policy == ReferrerPolicyToken.emptyString
          ? ReferrerPolicyToken.noReferrerWhenDowngrade.token
          : policy.token,
  ];
  return (innerHandler) {
    return (request) async {
      final response = await innerHandler(request);
      return response.change(
        headers: {'referrer-policy': args, ...response.headersAll},
      );
    };
  };
}