I found this great post to properly manage environment variables in a Nuxt v2.13 app. I simply tried to implement the proposed logic, but I am encountering some problems that I would like to ask you.
I set publicRuntimeConfig and privateRuntimeConfig as follow. I'm using Contentful, so I've to properly set Contentful tokens to be able to make API calls.
export default {
// Nuxt target - See https://nuxtjs.org/api/configuration-target
target: 'static',
// Nuxt rendering mode - See https://nuxtjs.org/api/configuration-mode
mode: 'universal',
// Both server and client.
publicRuntimeConfig: {
backendApi: process.env.BACKEND_API_URL
shopUrl: process.env.SHOP_URL
},
// Only available on server using same $config (it overrides publicRuntimeConfig)
privateRuntimeConfig: {
ctfSpaceId: CTF_SPACE_ID,
ctfCdaAccessToken: CTF_CDA_ACCESS_TOKEN,
ctfCpaAccessToken: CTF_CPA_ACCESS_TOKEN,
ctfEnvironment: CTF_ENVIRONMENT
},
Above to module export statement I've to define the data from .env, so:
require('dotenv').config()
const {
CTF_SPACE_ID,
CTF_CDA_ACCESS_TOKEN,
CTF_CPA_ACCESS_TOKEN,
CTF_ENVIRONMENT,
} = process.env
Next, moving in a Nuxt page component (pick pages/index.vue as reference ), remembering that privateRuntimeConfig is available only on server side, I boost asyncData hook with $config:
async asyncData({ app, $config: { ctfSpaceId, ctfCdaAccessToken } }) {
const $i18n = app.i18n
const client = contentful.createClient({
space: ctfSpaceId,
accessToken: ctfCdaAccessToken,
})
...
}
Cool, I refresh the browser tab where Nuxt is running, asyncData does its job and private config variables are suitably set.
Next, I browse other app pages, and come back to index and .
Nuxt crashed and $config private variables are undefined.
I don't want to find workarounds to this because we're talking about security and therefore I can only ask if my configuration is correct and what is happening to Nuxt under the hood.
Nuxt.js documentation is explicit:
asyncData is called every time before loading the page component. It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.
So the question is how to properly load private config variables on client side.
A fellow mentor friend would say the magic word: Noob.