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

3

11

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?

Radiotherapy answered 2/5, 2018 at 9:49 Comment(1)
there are few functions like asyncData, fetch, nuxtServerInit , these methods get executed in server side. Also you can try using middleware too.Need
S
11

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

Stevie answered 21/1, 2019 at 3:19 Comment(1)
Depending on your use-case it could error. Best to use something like: process.server ? req.headers.host : window.location.hostFictitious
J
3

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

Johannejohannes answered 25/9, 2023 at 20:51 Comment(0)
A
0

Something like below should work for you

asyncData ({ req, res }) {
  const hostname = req ? req.headers.host : window.location.host.split(':')[0]
}
Acerbate answered 20/2, 2023 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.