Often we have some settings to store, like the url of the API, credentials, some other data. Often it is provided to an application in a form of environment variables.
A nice workflow might be like so:
commit->test->build docker image and push it to registry
And when running, you can configure prebuilt image using environment variables without rebuilding.
Seems perfect,right? You may have thought that using normal
process.env.VARIABLE_NAME is enough. It is not.
During build time, webpack replaces
process.env.VARIABLE_NAME with actual variable from build environment, making images not reproducible and not configurable.
Nuxt docs on environment variables seem to provide a nice solution for that problem, but actually it works absolutely the same way.
So how do we do it properly?
If we have an SSR app, we have two stages: build and launch stage.
At launch stage we should load our environment variables.
This is were vuex comes in handy.
We can use nuxtServerInit, which will be run on server bootstrap(it also runs on client, but we need server side variable only).
In Nuxt.js 2.13+ you can use new Runtime config property. After configuring it in nuxt.config.js, you can access it anywhere via
But there are still some quirks! If you want to use environment variables in vuex getters, then
this.$config won't work.
So we still need to do the same process as described below, but replace
Put this code in
store/index.js file. Nuxt will activate vuex for you.
So, we define store state with the only variable
env, being empty object by default, this way we store all needed variables in one object.
Our mutation is just changing
nuxtServerInit is doing all the job.
We check if we run from server, and if so, we simply run our mutation, loading environment variables using same process.env. It doesn't get replaced by webpack in that case.
We can also set default values using
|| 'default value'.
And then, in any place in your code, you can access environment variable using
This is a pretty simple and working way to load environment variables dynamically, encouraging proper CI/CD workflow with minimal maintenance issues.
I think that this example should be put in nuxt docs. Let's create a pull request? (:
This example, as the previous post, came from my work on my opensource project bitcart.
(For example, any help with improving checkout design is highly appreciated)
I hope you found my article interesting, have a good day!