soarinblue
soarinblue

Reputation: 1687

nuxt js, how can I get the host name of a web page at server side rendering

At nuxtjs poroject, I have a configure variable of api environment like this:

[
{
  front_host: local-1.domain.com,
  backend_api: api-1.domain.com
},
{
  front_host: local-2.domain.com,
  backend_api: api-2.domain.com
},
]

I need get the right object element from the host name, for example, if the host name of my web page is "local-1.domain.name", then I shall get the object {front_host: local-1.domain.com, backend_api: api-2.domain.com}.

In nuxtjs, if the web page renders at the front end, then I can get host name by location.host, if at ssr(server side rendering), how can I get the host name?

Upvotes: 12

Views: 20546

Answers (3)

Remigius Stalder
Remigius Stalder

Reputation: 2170

in nuxt 3, you could also use:

const url = useRequestURL()
console.log('host name', url.hostname)

see: https://nuxt.com/docs/api/composables/use-request-url

Upvotes: 7

Muhammad Reda
Muhammad Reda

Reputation: 27033

Something like below should work for you

asyncData ({ req, res }) {
  const hostname = req ? req.headers.host : window.location.host.split(':')[0]
}

Upvotes: 0

Ash
Ash

Reputation: 131

Like@divine said, there are several options you could choose from.

For example,

export default {
     async asyncData ({ req, res }) {
        if (process.server) {
         return { host: req.headers.host }
        }
    }

host will be your ssr host name

Upvotes: 11

Related Questions