How can i get the full url in a Nuxt plugin?

Viewed 2977

I'm having trouble accessing the url in my nuxt js plugin that has all. In short: there is a part in the url that shows me what country people are visiting from and that country should be used in the api calls.

window.location doesn't work because it's SSR and window isn't available there.

req.headers.host doesn't work because nuxt generate has been run on the staging/production

Edit: The route object won't give me any info on the domain. Only parts after that. For example with www.test.nl/about it will not return www.test.nl anywhere

Is there a way i could get the full url in this scenario?

1 Answers

If it's really about the host, you can wrap your plugin code with a process.client check. This way your code only gets executed on the client and you can safely use window.location.host.

If the current route without the host is enough, you can use the route object, which is part of the context object which gets passed to your plugin (Works on server and client).

export default function ({ route }) {
  if (process.client) {
    console.log(window.location.host)
  }

  console.log(route)
}
Related