Reputation: 63
I'm building a website with Gridsome and Netlify CMS, hosted with Netlify.
The Netlify CMS stuff is located in /static/admin
.
I'm manually initializing the Netlify CMS in an index.js
to change the branch on which it pushes depending on an environment variable.
const branch = window.GRIDSOME_CMS_BRANCH || "develop"
window.CMS_MANUAL_INIT = true
const { CMS, initCMS: init } = window
init({
config: {
backend: {
branch: `${branch}`
},
},
})
I'm setting these environment variables in the netlify.toml
file like this:
[context.release.environment]
GRIDSOME_CMS_BRANCH = "release"
[context.stage.environment]
GRIDSOME_CMS_BRANCH = "stage"
[context.develop.environment]
GRIDSOME_CMS_BRANCH = "develop"
But when I build and navigate to mysite.com/admin
to access the CMS, the branch always is develop
and the environment variable is undefined
. I tried many different things and I guess I have some basic misconception about environment variables in this context. I'd be a happy man if anyone could help me out and explain this stuff to me or provide a working solution.
Thanks in advance and cheers!
Upvotes: 3
Views: 378
Reputation: 185
I had a similar issue which I solved using the technique described in this article https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5
If you need to access the environment variables on the client side (this is where the Netlify CMS is initialized) you can use webpack to store that value for you at build time.
You can do something like this in the webpack config for Netlify CMS:
const webpack = require('webpack');
const getRepoInfo = require('git-repo-info')
const { branch } = getRepoInfo()
module.exports = () => {
return {
plugins: [
new webpack.DefinePlugin({
'process.env.GRIDSOME_CMS_BRANCH': JSON.stringify(branch)
})
]
};
The above code is executed on the server at build time but makes the variable process.env.GRIDSOME_CMS_BRANCH
available to the client at runtime.
Upvotes: 1