I'm using gatsby-node to call two separate servers to get some data. I need different URL's for production, staging and development. I can access the NODE_ENV via process.env.NODE_ENV but if I set any other variable (i.e. process.env.GATSBY_ENV) I'm unable to access that.
Update your package.json to include the following scripts:
"build": "gatsby build GATSBY_ENV=production",
"develop": "gatsby develop GATSBY_ENV=development",
"staging": "gatsby develop GATSBY_ENV=staging",
in gatsby-node.js add the following:
console.log(process.env.GATSBY_ENV, "this is the environment!")
and run yarn staging
The expected result should be:
"staging, this is the environment"
"undefined, this is the environment"
System:
OS: macOS 10.14.3
CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 10.1.0 - ~/.nvm/versions/node/v10.1.0/bin/node
Yarn: 1.15.2 - /usr/local/bin/yarn
npm: 5.6.0 - ~/.nvm/versions/node/v10.1.0/bin/npm
Browsers:
Chrome: 74.0.3729.131
Safari: 12.0.3
npmPackages:
gatsby: ^2.3.29 => 2.3.29
gatsby-image: ^2.0.40 => 2.0.40
gatsby-plugin-manifest: ^2.0.29 => 2.0.29
gatsby-plugin-offline: ^2.0.25 => 2.0.25
gatsby-plugin-react-helmet: ^3.0.12 => 3.0.12
gatsby-plugin-sharp: ^2.0.35 => 2.0.35
gatsby-plugin-sitemap: ^2.0.12 => 2.0.12
gatsby-plugin-web-font-loader: ^1.0.4 => 1.0.4
gatsby-source-filesystem: ^2.0.32 => 2.0.32
gatsby-transformer-sharp: ^2.1.18 => 2.1.18
So I should mention I tried dotEnv and cross-env with no luck as well.
Try changing the scripts to
"build": "GATSBY_ENV=production gatsby build",
"develop": "GATSBY_ENV=development gatsby develop",
"staging": "GATSBY_ENV=staging gatsby develop",
Ding ding ding - that's the winner ^ 馃う鈥嶁檪
^ didn't work for me, but changing the filename to .env.development
and prefixing the variables with "GATSBY_" did.
Even I faced this issue while deploying the gatsby application over netlify, a workaround is using the above fix provided by @aravindballa i.e. by setting the env variables before final command to be set in netlify _Build command_
Most helpful comment
Try changing the scripts to