Search code examples
vue.jsvuexnuxt.jsstore

Declare URL of Api once in entire Nuxt.js app


I am using a CMS to populate my Nuxt.js app and declaring the api URL as following.

in nuxt.config.js, to generate dynamic routes, I have:

  const apiUrl = 'http://xxx.xx.xx.xx:xxxx'

  generate:{
    routes: function () {
      return axios.get(apiUrl + '/pages')
        .then((res) => {
          return res.data.map(page =>{
            return page.slug
          })
      })
    }
  },
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: apiUrl + '/graphql'
      }
    }
  }

in store/index.js, to be accessible in my layout, pages and components, I have:

export const state = () => ({
  apiUrl: 'http://xxx.xx.xx.xx:xxxx'
})

As you can see, the downside here is that the const is declared in two different places, which might be not a big deal but feels "wrong" to me. It seems not possible to get data from the store in the nuxt.config,js, and not possible to get data from nuxt.config.js into my pages/components unless importing it every time. Is there not a more clean way to set this up, or am I doing it in the wrong way anyway?

EDIT

I might have also complicated my question. Basically what I need in my Layout, Pages and Components it's the pure apiURL. This is needed to be the first part of the url when I load images from the api.

I am using apollo so I get all the data with that, but the image urls are returned like uploads/image_name.jpg. This means that really what I need is the httpEndpoint (from the apollo settings inside nuxt.config.js) to be available in my components as part of the full images url.

Thanks


Solution

  • What you want is an environment variable.

    Here it is described in more detail. https://nuxtjs.org/api/configuration-env/

    What I prefer over it is the .dotenv module https://github.com/nuxt-community/dotenv-module

    You would simply make an .env file in the root of your project and write down:

    API_URL=http://xxx.xx.xx.xx:xxxx
    

    Then you can use it everywhere in your components, pages etc. through the process and context. this.$process.env.API_URL

    If you also wanna use that variable inside your nuxt.config.js you can simply require('dotenv').config() and use it there too.