llanfair
llanfair

Reputation: 1885

Nuxt - Axios requests on server side not sending referer

The story

My backend app provides SEO information for my sites pages. One of this informations are OpenGraph meta tags, such as og:type and og:url. og:url value is given by the API through the HTTP "Referer" header.

What I'm doing now

I'm using Axios module to make my requests. Through asyncData function in my pages I can get the req variable and it's headers.referer property, which is what I want, like this:

// page.vue
async asyncData({ app, req }) {
  app.$axios.setHeader('Referer', req.headers.referer);
}

The problem

If I am at the index page, let's say, then I click in a link to a dynamic page I got an error, for req is not available on asyncData function while navigating, I suppose.

The question

How can I dynamically get my requests referers to send it with Axios request for both client-side and server-side requests?

Info about the versions:

Upvotes: 2

Views: 10019

Answers (1)

Aldarund
Aldarund

Reputation: 17621

You can do something like this:

async asyncData({ app, req }) {
  const referrer = process.client ? window.document.referrer :  req.headers.referer
  app.$axios.setHeader('Referer', referrer)
}

Upvotes: 3

Related Questions