iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔗

How to Get the Referer Header on the Server Side

に公開
2025/06/11

What is a referer?

A referer is information indicating the source of access to a web page and is included in the request headers.
For example, if you access a site by clicking from a Google search results page, the referer will include the URL "https://www.google.com".

Referers are used in fields like website traffic analysis and SEO.
By analyzing referer information, you can understand which page the access originated from.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer

Conditions under which the referer is set

The conditions under which the referer is set are as follows:

  • Transition from HTTPS to HTTPS
  • Transition from HTTPS to HTTP
  • Transition from HTTP to HTTP

Note that the referer is not set in the following cases, so caution is required:

  • Transition from HTTP to HTTPS
  • Transition from another domain

How to get referer information

To get referer information, there are methods to obtain it on the client side and methods to obtain it on the server side using a framework.

Using JavaScript

When using JavaScript, you can obtain referrer information on the client side using document.referrer.

console.log(document.referrer);

Obtaining on the server side

While referers are set in the request by the browser automatically, if you want to obtain them on the server side, you can do so using features built into frameworks.

How to obtain in Nuxt

In Nuxt, you can obtain referrer information using req.headers.referer from the context within the asyncData method.

export default {
  async asyncData({req}) {
    const referer = req.headers.referer
    return {}
  }
}

How to obtain in Next

In Next.js as well, you can obtain referrer information using req.headers.referer from the context within API routes or the getServerSideProps method of page components.

export async function getServerSideProps({req}) {
  const referer = req.headers.referer
  return { props: {} }
}

Thoughts

I needed to obtain the referer on the server side because I had to include it in the API request header. While it seems that the acquisition itself is possible using framework features, it seems necessary to consider whether it's actually appropriate to obtain the referer from a security perspective, and to what extent the referrer policy should be configured.
I would like to make the appropriate settings after also researching referrer policies.
The following article was very helpful.

https://web.dev/referrer-best-practices/

Discussion