user2779340
user2779340

Reputation: 21

How can I get the request hostname in nuxt.config.js/i18n?

I am trying to dynamically set the baseUrl property of nuxt/i18n depending on the request headers in nuxt.config.js

nuxt.config.js

i18n: {
    baseUrl: ({ req }) => {
      return "https://" + req.headers.host;
    }
},

This doesn't work. Is there any way to access the request headers?

Nuxt: v2.15.7

i18n/nuxt: v7.0.1

Upvotes: 1

Views: 1452

Answers (2)

user2779340
user2779340

Reputation: 21

Finally, found another solution. Nuxt.config.js is processed both on server side and client side with different contexts. At the server side I obtain the request host header and pass it to the client side through nuxtState. More info here: https://nuxtjs.org/docs/2.x/internals-glossary/context#beforenuxtrender

nuxt.config.js

i18n: {
    baseUrl: (context) => {
      // get the hostname from http request headers on the server side and save it to nuxtState
      if (process.server) {
        const { req, beforeNuxtRender } = context;
        beforeNuxtRender(({ nuxtState }) => {
          nuxtState.host = req.headers.host;
        });
      }
      return (
        "https://" +
        (process.server ? context.req.headers.host : context.nuxtState.host)
      );
    },
...
},

Upvotes: 1

kissu
kissu

Reputation: 46696

You can use serverMiddleware in your nuxt.config.js file

serverMiddleware: ['~/server-middleware/logger']

~/server-middleware/logger.js

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

And maybe set a cookie or alike, then use it in your nuxt.config.js for the other modules.


Otherwise, it is also used in the Nuxt context: https://nuxtjs.org/docs/2.x/concepts/context-helpers
So, either asyncData, plugins, middleware or nuxtServerInit.

Upvotes: 0

Related Questions