Philipp S.
Philipp S.

Reputation: 981

Get current domain name from request in Nuxt

How can I get the current domain name from a request on server side?

My Nuxt based website is reachable from different domains. I would like to get the domain name from where the user has accessed the website. How can I do this?

I tried to write a middleware for that purpose but it always displays localhost:3000

export default function({ store, req }) {
  if (process.server) store.commit('hostname', req.headers.host)
}

Any idea how to fix this issue?

Upvotes: 8

Views: 10855

Answers (2)

agm1984
agm1984

Reputation: 17132

If you are using Vuex, you can use the nuxtServerInit action to access the request headers.

In my example, I am storing the domain in Vuex so it can be accessed anywhere in the application because this middleware fires before all other ones.

store/index.js

export const state = () => ({
    domain: '',
});

export const mutations = {
    setDomain(state, domain) {
        state.domain = domain;
    },
};

export const actions = {
    nuxtServerInit(store, context) {
        store.commit('setDomain', context.req.headers.host);
    },
};

export const getters = {
    domain: (state) => state.domain,
};

middleware/domain.js

export default function ({ route, store, redirect }) {
    console.log('hey look at that', store.getters['domain']);
}

nuxt.config.js

export default {
    ...

    router: {
        middleware: 'domain'
    },
}

Upvotes: 6

Villapalos
Villapalos

Reputation: 717

I'm able to get the domain name declaring the function on the server by this way:

export default function (req, res, next) {
    console.log(req.headers.host)
}

If you need to commit the data to the store, saving data in the environment and recover it on the client side could be a solution.

Upvotes: 1

Related Questions