Best practices for setting your Referral Policy and using the referral in incoming requests.
Updated
Safe and secure
Summary
- The unexpected leak of cross-origin information hampers the privacy of web users. A protective referral policy can help.
- Consider establishing a referral policy of
strict-origin-when-cross-origin. It preserves much of the sender's usefulness, while mitigating the risk of leaking cross-data sources. - Do not use cross-site request forgery (CSRF) referrals. Use CSRF tokens
en su lugar, y otros headersConcepto de Encabezados¿Qué son los Encabezados?Los Encabezados, además conocidos como headers en inglés, son una parte fundamental del diseño de cualquier web, dado que consiste en la parte principal que se ve de esta al acceder, la parte de arriba de cualquier página. El lugar más visible y al que todos los usuarios que visitan un lugar de Internet acceden cuando entran en él, pudiendo tener así una imagen rápida plus como una capa adicional de seguridad.
Before we start:
- If you are unsure of the difference between 'site' and 'origin', see Understanding 'same site' and 'same origin'.
- the
RefererThe heading is missing an R, due to an original misspelling in the specification. the
Referrer-Policyheader andreferrerin JavaScriptJavaScript es un lenguaje de programación que funciona en el lado del cliente y con el que las webs pueden ser más funcionales. Incorporación en código HTML El código JavaScript puede ser incrustado en las páginas HTML, para que adquieran funcionalidad. Existen varias opciones. Puede estar entre las etiquetas <SCRIPT> y </SCRIPT>, puede estar contenido en un archivo externo, puede ser un parámetro de las etiquetas HTML, y puede estar plus y DOM están escritos correctamente.
Referer and Referer-Policy 101
Las solicitudes HTTPEl HTTP (Hyper Text Transfer Protocol) es un protocolo que se usa para transmitir datos en redes. HTTP es un estándar técnico generalmente aceptado que establece cómo un cliente web se comunica con un servidor para que los datos solicitados por el cliente puedan ser cargados y mostrados. Información general Junto con el URL y el HTML, HTTP es uno de los conceptos más importantes de Internet (www). Fue desarrollado plus pueden incluir el opcional Referer
header, que indica el origen o la UrlEl URL (Localizador Uniforme de Recursos), es una dirección definida que apunta a la posición de un archivo en un servidor y lo recupera. Las URL se introducen en un navegador web para ingresar a documentos en la web o se incrustan como hipervínculos dentro de un documento. Se puede usar un Permalink para que una URL esté disponible de forma permanente. Componentes de una URL • prefijo de protocolo plus de la página web desde la que se realizó la solicitud. los Referrer-Policy
header defines what data is available in the Referer header.
In the following example, the Referer The header includes the full URL of the page in site-one from where the request was made.

the Referer The header can be present in different types of requests:
- Solicitudes de navegación, cuando un usuario hace clic en un linkConcepto de Dominio¿Qué es un Enlace?En Internet, un link, además conocido como enlace o hipervínculo, es cualquier texto o imagen que se encuentra en una página web y en la que el usuario puede pulsar o clicar para ser dirigido a otro contenido distinto. Es el principal medio de “desplazamiento” en la red, puesto que se encuentra presente en prácticamente cualquier portal que visites a día de hoy, inclusive en plus
- Solicitudes de subrecursos, cuando un browserUn navegador (además: browser) es una herramienta informática que te permite ver documentos y datos y navegar por la red. Los navegadores pueden mostrar distintos tipos de recursos de información; principalmente documentos HTML, a pesar de todo, además son posibles otros tipos de archivos y contenido multimedia, como PDF, JPEG, MPEG, GIF o el lenguaje de meta marcado. A través el uso de complementos especiales y la configuración respectivo, los plus solicita imágenes, iframes, scriptsConcepto de Scripts¿Qué son los Scripts?Los Scripts son fragmentos de código que se usan para dar forma a herramientas tanto en Internet como en el sector de la informática en general. Son una parte crucial del software, puesto que se trata exactamente del código que conforma a una aplicación en su totalidad o a una de sus funciones, como además el que puedes hallar explorando cómo está hecha una web.Desde plus y otros recursos que necesita una página.
For navigations and iframes, this data can also be accessed via JavaScript using
document.referrer.
the Referer The value can be revealing. For example, an analytics service might use the value to determine that the 50% of visitors from site-two.example He came from social-network.example.
But when the full url including the path and the query string is sent in the Referer through origins, this could be hinder privacy and pose security risks as well. Take a look at these URLs:

URLs 1 to 5 contain private information, sometimes even identifying or confidential. Silently filtering them through sources can compromise the privacy of web users.
The URL n. 6 is a Capacity url. You don't want it to fall into the hands of anyone other than the intended user. If this happens, a malicious actor could hijack this user's account.
To restrict what referral data is available to requests from your site, you can set a referral policy.
What policies are available and how are they different?
You can select one of eight policies. According to the policy, the data available from the Referer
header (and document.referrer) can be:
- No data (no
Refererheader is present) - Just the origin
- The full URL: source, path, and query string

Some policies are designed to behave differently depending on the context- Cross-origin or same-origin request, security (if the request destination is as secure as the origin), or both. This is useful for limiting the amount of information shared between origins or for less secure origins, while maintaining the richness of the referrer within your own site.
Here is an overview showing how referral policies restrict available url data in referrer header and document.referrer:

MDN provides a full list of policies and behavior examples.
Things to keep in mind:
- Todas las políticas que tienen en cuenta el esquema (HTTPSHTTPS (protocolo de Transferencia de Hiper-Texto) es un protocolo que permite determinar una conexión segura entre el servidor y el cliente, que no puede ser interceptada por personas no autorizadas. En resumidas cuentas, es la versión segura de el http (Hyper Text Transfer Protocol) Cómo funciona Una conexión HTTP estándar en Internet puede ser fácilmente secuestrada por partes no autorizadas. El propósito de una conexión HTTPS es evitar esto: encriptar plus frente a HTTP) (
strict-origin,
no-referrer-when-downgradeandstrict-origin-when-cross-origin) treat requests from an HTTP source to another HTTP source in the same way as requests from an HTTPS source to another HTTPS source, even if HTTP is less secure. That's because for these policies, what matters is whether a security degrade occurs, that is, if the request can expose data from an encrypted source to an unencrypted one. An HTTP → HTTP request is not encrypted all the time, so there is no degradation. HTTPS → HTTP requests, on the other hand, have a degradation. - If a request is same origin, this means that the scheme (HTTPS or HTTP) is the same; therefore, there is no security degradation.
Políticas de referencia predeterminadas en los browsersConcepto de Navegadores¿Qué son los Navegadores?Los Navegadores son herramientas informáticas que utilizamos para, normalmente, navegar por Internet y visitar cualquier página web, al mismo tiempo de para hacer otras tareas como ver documentos, observar vídeos o reproducir contenido multimedia de cualquier tipo. Son un tipo de software sencillamente usual y bastante utilizado hoy en día.Insistimos en que es algo que se utiliza con mucha frecuencia, puesto que moverse por Internet plus
As of July 2020
If no referral policy is set, the default browser policy will be used.
| Browser | Default Referrer-Policy / Behaviour |
|---|---|
| Chrome |
Planning to switch to |
| Firefox |
|
| Edge |
|
| Safari |
Similar to |
Setting up your referral policy: best practices
objective¿Qué es un objetivo?En marketing, un objetivo es el resultado que se pretende alcanzar en un periodo de tiempo, a través el uso de los recursos disponibles. Por tanto, se debe formular de una forma clara y hace falta que sea accesible y medible. plus: Explicitly establish a privacy enhancement policy, such as
strict-origin-when-cross-origin(or stricter).
There are different ways to set referral policies for your site:
You can set different policies for different pages, requests, or items.
The HTTP header and meta element are at the page level. The order of precedence when determining the effective policy of an item is:
- Element-level policy
- Page level policy
- Default browser
Example:
indexUn index o índice es generalmente un directorio en un orden específico que se usa con fines de orientación. En términos de motores de búsqueda, un índice es la lista de páginas web que es emitido por el motor de búsqueda en respuesta a una solicitud de búsqueda del usuario. Información general La lista que se muestra posteriormente de introducir una solicitud de búsqueda específica se llama SERPs (Search Engine plus.html:
<meta yam="referrer" content="strict-origin-when-cross-origin" />
<img src="..." referrerpolicy="no-referrer-when-downgrade" />
The image will be requested with a no-referrer-when-downgrade policy, while all other child resource requests on this page will follow the strict-origin-when-cross-origin politics.
How to see the referral policy?
When inspecting an HTTP request:
- In Chrome, Edge, and Firefox, you can see the
Referrer-Policy. - In Chrome, Edge, Safari, and Firefox, you can see the
Referer.

Chrome DevTools, Net panel with a selected request.
What policy should you set for your website?
Summary: Explicitly set a privacy enhancement policy as strict-origin-when-cross-origin (or stricter).
Why "explicitly"?
If no referral policy is set, the default browser policy will be used; in fact, web sites often yield to the browser's default. But this is not ideal, because:
- The default browser policies are
no-referrer-when-downgrade,
strict-origin-when-cross-originor stricter, depending on the browser and mode (private / incognito). Therefore, your website will not behave predictably in all browsers. - Browsers are adopting stricter defaults, such as
strict-origin-when-cross-originand mechanisms like reference clipping for cross-origin applications. Explicitly opting for a privacy enhancement policy before browser defaults change gives you control and helps you run the tests as you see fit.
Why strict-origin-when-cross-origin (or more strict)?
You need a policy that is secure, that enhances privacy, and that is helpful; what "helpful" means depends on what you want from the sender:
- Sure- If your website uses HTTPS (if not, make it a priority), you don't want your website URLs to be leaked in non-HTTPS requests. Since anyone on the network can see them, this would expose your users to person-in-middle attacks. The police officers
no-referrer-when-downgrade,
strict-origin-when-cross-origin,no-referrerandstrict-originSolve this problem. - Privacy enhancement: for a cross-origin request,
no-referrer-when-downgradeshare the full url; this does not improve privacy.strict-origin-when-cross-originandstrict-originonly share the origin, andno-referrerdoes not share anything at all. This leaves you with
strict-origin-when-cross-origin,strict-originandno-referreras options to improve privacy. - Useful:
no-referrerandstrict-originnever share the full url, even for requests from the same origin, so if you need this,strict-origin-when-cross-originit is a better option.
All this means that strict-origin-when-cross-origin it is generally a sensible option.
Example: set a strict-origin-when-cross-origin politics:
index.html:
<meta yam="referrer" content="strict-origin-when-cross-origin" />
O del lado del serverLos servidores son ordenadores centrales y potentes dentro del campo de la tecnología de la información que procesan y proporcionan software y archivos en una red. Desde el punto de vista de un cliente, varios ordenadores en una red pueden ponerse en contacto con el servidor central para conseguir la información solicitada. En la arquitectura cliente-servidor, el servidor puede ser un software que proporciona un servicio y se ejecuta en plus, por ejemplo en Express:
const helmet = require('helmet');
appConcepto de APP¿Qué es una APP?Una App es todo aquel programa que se ejecuta desde una interfaz teléfono celular, es decir, desde un móvil o una tablet. Consiste en la herramienta principal para cualquier usuario que tenga un teléfono teléfono celular, de todo el software que se mueve en tiendas digitales como Google Play Store o la App Store y que tanto se adentra en cualquier terminal moderno.Es un concepto plus.use(helmet.referrerPolicy({policy: 'strict-origin-when-cross-origin'}));
What if strict-origin-when-cross-origin (or stricter) doesn't suit all your use cases?
In this case, don't set an insecure policy like unsafe-url. What you can do instead is take a
progressive approach- Set a protection policy for your website and, if necessary, a more permissive policy for specific requests or items.
Example:
index.html:
<meta yam="referrer" content="strict-origin-when-cross-origin" />
<img src="…" referrerpolicy="no-referrer-when-downgrade" />
script.js:
fetch(url, {referrerPolicy: 'no-referrer-when-downgrade'});
One policy per item is not supported by all browsers browsers (Examples: referrerpolicy for to
elements, for img elements, and to link elements). But browsers that don't support this tend to take a strict approach anyway (e.g. all cross-origin requests will be set Referer to the origin).
What else should you consider?
Your policy should depend on your website and use cases; this is up to you, your team and your company. If some URLs contain identifying or confidential data, establish a protection policy.
Warning: Data that may not seem sensitive to you may be sensitive to your users, or it is simply not data that you want or hope to silently filter for cross-origin.
Using the incoming request reference: best practices
Cross-Site Request Forgery Protection (CSRF)
Using the referral of incoming requests for CSRF protection has some difficulties:
- It can be hidden with the
no-referrerpolicy, or falsified by the issuer of the request. If you have no control over the implementation of the request issuer, you cannot make assumptions about any header that you receive. - the
Refererheader (anddocument.referrer) can contain more data than you needFor example, a full URL when you just want to know if the request is cross-sourced.
Use CSRF tokens
as your primary protection instead. For added protection, use SameSite, and instead of Referer, you can use headings like
Origin (disponible en solicitudes POSTConcepto de Post¿Qué es un Post?Un Post es todo aquel contenido, sea post, opinión, noticia u otro género, que un autor publica en un blog. Este puede ser de carácter corporativo o meramente ocioso; pero siempre tiene como meta arrojar información o reflejar una idea, al mismo tiempo de facilitar que los usuarios encuentren la web donde se recoge por medio de de buscadores y demás plataformas online.Generalmente, se han plus y CORS) y
Sec-Fetch-Site (if available).
Login
the Referer header (and document.referrer) may contain private, personal or identifying data, so it should be treated as such.
And instead of Referer, consider using other headers that may address your use case:
Origin and
Sec-Fetch-Site.
Payments
Payment providers can trust Referer header of incoming requests for security checks.
For example:
- The user clicks on a Buy on button
online-shop.example / cart / checkout. online-shop.exampleredirect topayment-provider.exampleto manage the transaction.payment-provider.examplecheck theRefererof this application against an allowed list
Referervalues set by merchants. If it does not match any entry in the list,
payment-provider.examplerejects the request. If it matches, the user can continue with the transaction.
Best practices for payment flow security controls
Summary: As a payment provider, you can use the Referer as a basic check against naive attacks, but you should definitely have another more reliable verification method in place.
the Referer The header alone is not a reliable basis for a verification - the requesting site, whether a legitimate merchant or not, can easily establish a no-referrer policy that will make the Referer
information not available to the payment provider. However, as a payment provider, looking at the
Referer can help you catch naive attackers who did not establish a no-referrer politics. Then you can decide to use the Referer as the first basic check. If you do that:
- Don't wait for the
Refererbe always present; and if it is present just check with the piece of data it will include as a minimum: the origin. When configuring the allowed list
Referervalues, make sure no path is included, just the origin. Example: the allowed
Referervalues foronline-shop.exampleIt should beonline-shop.exampledo not
online-shop.example / cart / checkout. Why? Because by waiting or notRefererat all or a
Referervalue which is the origin of the requesting website, avoid unexpected errors as it is make no assumptions about theReferrer-PolicyYour merchant has established or on the behavior of the browser if the merchant does not have an established policy. Both the site and the browser could remove theReferersent in the incoming request only to the origin or not send theRefererabsolutely. - If he
Refereris absent or is present and yourRefererorigin verification was successful - you can move on to your other more reliable verification method (see below).
What is a more reliable verification method?
A reliable verification method is to allow the applicant hash the request parameters along with a unique key. As a payment provider, you can calculate the same hash on your side and only accept the request if it matches your calculation.
What's the matter with him Referer When does an HTTP merchant site with no referral policy redirect to an HTTPS payment provider?
No Referer will be visible in the request to the HTTPS payment provider, because most browsers use strict-origin-when-cross-origin or
no-referrer-when-downgrade by default when a website does not have a policy in place. Also note that Change Chrome to a new default policy it will not change this behavior.
conclusion
A protective referral policy is a great way to give your users more privacy.
For more information on the different techniques to protect your users, check out the safe and secure collection of web.dev.
Many thanks for contributions and comments to all reviewers, especially Kaustubha Govind, David Van Cleve, Mike West, Sam Dutton, Rowan Merewood, Jxck, and Kayce Basques.
Means




