2

In my nuxt.config.js file I create some variables which are needed in multiple parts of my application. My main objective is this:

In this example I use the about.vue page. The name and url of a link are defined in the nuxt.config file. An object is created that stores both custom name as url of about. I want to replace the standard URL of homepage.com/about to homepage.com/custom-about. I should get custom-about from the $config.ABOUT.URL. I tried both $config.ABOUT.URL as this.ABOUT.URL but both won't work. How can I pass the variable created in publicRuntimeConfig to router inside the same nuxt.config.js file?

.env

ABOUT_NAME='Custom about'
ABOUT_URL='custom-about'

nuxt.config.js

publicRuntimeConfig: {
  PAGE_TITLE: process.env.PAGE_TITLE || "Company",

  ABOUT: {
    NAME: process.env.ABOUT_NAME || "About us",
    URL: process.env.ABOUT_URL || "/about"
  },
}
...
router: {
  extendRoutes: routesIn => {
    routesIn.forEach(r => {
      if (r.path.includes("/about")) {
      r.path = r.path.replace("/about","/" + this.ABOUT.URL);
    }
  }
},
kissu
  • 40,416
  • 14
  • 65
  • 133
  • Hi, does this one help? https://stackoverflow.com/a/67705541/8816585 – kissu Nov 17 '21 at 17:59
  • Hi, thanks for your reply. Unfortunately, this doesn't help. This explains how to use the variables in other documents/components. This works just fine. I need to pass the variables inside the nuxt.config file. – Jeffrey van Zwam Nov 18 '21 at 08:54
  • 1
    Hi, unfortunately not. But I found out that it is possible to write plain JS between the import and export section, so this allows me to create an object which I can use throughout the full document. – Jeffrey van Zwam Nov 23 '21 at 08:38

1 Answers1

2

In my comment, there is a part with If you need this variable for a Nuxt module, but yeah, I'll edit it to basically add ... or anything at all in your nuxt.config.js file I guess.

Here, you should use this

r.path = r.path.replace("/about", "/", process.env.ABOUT_URL)
kissu
  • 40,416
  • 14
  • 65
  • 133
  • Unfortunately I don't need the value from process.env but from $config. – Jeffrey van Zwam Nov 18 '21 at 11:53
  • @JeffreyvanZwam You don't have access to `$config` in `nuxt.config.js`. As explained [here](https://nuxtjs.org/docs/concepts/context-helpers), `$config` is available in Nuxt's context aka in `asyncData`, `plugins` , `middleware` and `nuxtServerInit`. Why couldn't you use `process.env` here? – kissu Nov 18 '21 at 11:56