I'd like to set some envionment variables and read them from my site, but I haven't found a way to do so.
If I run FOO=foo npm run dev
There is no way to read that FOO variable, as far as I know.
console.log(process.env) returns only {NODE_ENV: "development"}
Any way to solve that ?
Is it supported ?
Thanks
Javascript in Webpack isn't the same as Javascript within Node. So to get an environmental variable from the node context into Webpack, you have to bridge the gap. By default, Gatsby passes in process.env.NODE_ENV but nothing else.
To add additional environmental variables you'll need to use the modifyWebpackConfig API which gets passed a config object that can use like in core to set custom globals within your project.
https://github.com/gatsbyjs/gatsby#how-to-use-your-own-webpack-loaders
I missed this part of the doc, thank you.
create-react-app provides an unified way to define and use environment variables. It is very convenient. Wouldn't it be interesting to have a similar feature with Gatsby ?
With Gatsby, these variables (for example, a Google Analytics UA code) have to be added to config.toml or somewhere else in the versioned code. It would be better, though, if the code could stay clean of them, as advised in https://12factor.net/config.
Sure, there is the modifyWebpackConfig way, but I think having this feature supported by Gatsby would be nicer.
Oh wow yes! Let's absolutely copy that. I am a big fan of using environmental variables just didn't occur to me that we could make it cleaner. The main thing I'd want to avoid is bringing over all the crap shell default env variables which I'm assuming/hoping CRA does.
Could you take this on and add a PR?
Awesome, glad you like the suggestion !
I'm really busy atm, but hell, I guess it applies to you and everyone here as well.
I'm not familiar with Gatsby internals, so you'd probably be way faster implementing that.
Otherwise, let me know and I'll do my best to find some time for that soon.
Immense congrats for Gatsby btw, most fantastic blog engine I've ever used ! :+1: :)
Quick question:
In create-react-app, env variables are considered and passed down only if they start with REACT_APP_.
For example, here is how one of my .env (dotenv) files looks like:
REACT_APP_API_URL=http:// ...
REACT_APP_AUTH_API_URL=http://...
REACT_APP_FACEBOOK_APP_ID=...
REACT_APP_FACEBOOK_FIELDS=...
REACT_APP_FACEBOOK_SCOPE=...
The value of this is not clear to me though, I'd rather have env variables non-prefixed (their values tend to always stay the same, event if I migrate from one blog engine to an other). Any thoughts on this? In our case, should the env variables be required to be prefixed with GATSBY_ ?
The reason they did that I'm assuming is that most people's shells are littered with environment variables. E.g. mine looks like
Kyles-MacBook-Pro-2:gatsby (master=)$ env
TERM_PROGRAM=iTerm.app
TERM=xterm
SHELL=/bin/bash
TMPDIR=/var/folders/79/hy76bb9j0jlbs3kzr6mz45yc0000gn/T/
Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.fG7tdrI8PL/Render
TERM_PROGRAM_VERSION=3.0.12
TERM_SESSION_ID=w0t13p0:DB3B3D19-4479-4715-8F93-0B07D13C4501
COMMAND_MODE=unix2003
SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.000s5uoseh/Listeners
__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0
PATH=/usr/local/sbin:/usr/local/bin:/var/lib/gems/1.8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/MacGPG2/bin:/usr/texbin
PWD=/tmp/gatsby
EDITOR=vim
LANG=en_US.UTF-8
ITERM_PROFILE=Default
XPC_FLAGS=0x0
PS1=\[\e[1;36m\]\h:\W\[\e[m\]\[\e[1;32m\]$(__git_ps1 " (%s)")\[\e[m\]\[\e[1;36m\]$ \[\e[m\]
XPC_SERVICE_NAME=0
SHLVL=1
COLORFGBG=15;0
ITERM_SESSION_ID=w0t13p0:DB3B3D19-4479-4715-8F93-0B07D13C4501
DISPLAY=/private/tmp/com.apple.launchd.gdz6rLlb2q/org.macosforge.xquartz:0
_=/usr/bin/env
If we let in every environment variable, then all of those would get shipped along with whatever site I build which would a) be wasteful and b) potentially a security leak if you have sensitive info in an env var (I took a few out of the above actually 馃槃 ).
I've been thinking trying to get env vars to work with my gatsby site recently too. Might plugging this in be useful? https://www.npmjs.com/package/dotenv-webpack I'm pretty new, not sure how to go about trying to integrate it if it would be helpful.
Posted this here. This is my current workaround:
const env = {
production: {
analyticsId: 'UA-11111111-1',
api: {
url: 'https://api.google.com',
},
},
development: {
analyticsId: 'UA-00000000-0',
api: {
url: 'http://localhost:3000'
},
},
};
export default env[process.env.NODE_ENV] || {};
import env from 'env';
console.log(env.api.url);
Granted, this only let's you have 2 environments. development and production. I also created a env.example.js file for the repo so we don't have security keys/tokens committed to the repo.
I think copying the React App pattern and adding support for GATSBY_* env variables is a great start. Perhaps in the future we can add support for .env files as well. Anyone want to take this on?
@0x80 had a good idea that for v1 we could also provide an action creator for directly setting environment variables https://github.com/gatsbyjs/gatsby/issues/1033#issuecomment-303640235
If it's helpful in any way, this is what I've done and it seems to work well:
var webpack = require('webpack');
exports.modifyWebpackConfig = function(config, stage) {
config.merge({
plugins: [
new webpack.DefinePlugin({
'process.env': {
BUILD_ENV: JSON.stringify(process.env.BUILD_ENV ? process.env.BUILD_ENV : 'test')
}})
],
})
return config
}
@KyleAMathews I鈥檓 not sure #1462 fully addressed this since there鈥檚 still no way to pass in true ENV vars without adding a file. This precludes e.g. using Netlify鈥檚 built-in ENV var management.
Right https://github.com/gatsbyjs/gatsby/pull/1462#issuecomment-314612131
Would love a PR from you adding support for this!
Would this project be open to add config files to whitelist non prefixed host env variables?
Something like .env.production.host ?
SOME_HOST_ENV_VAR_NAME_1
SOME_HOST_ENV_VAR_NAME_2
// whitelisted env var are either in the whitelist file or prefixed by GATSBY_
var whitelistedVarObject = Object.keys(process.env).reduce(function (acc, key) {
if (key.match(/^GATSBY_/) || whitelist.includes(key)) {
acc[key] = JSON.stringify(process.env[key]);
}
return acc;
}, {});
@quentin- did you see this page? We do support .env.production files
Not sure if what you're proposing is different. If it is, please post a new issue to track the discussion there!
Hi @KyleAMathews how about if I want to have .env.test or something else .env.beta??? There is any possibility to have more than only develop and production?
@HuuDuc it's really .env${process.env.NODE_ENV} so things other than .env.develop would work. We force production builds to production as many things during the build would break otherwise.
So is there no way of achieving the following while using .env.develop|production?
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.SPACE_ID,
accessToken: process.env.ACCESS_TOKEN,
},
},
In gatsby-config.js
The problem here is that so many gatsby plugins use process.env.NODE_ENV, for example gatsby-plugin-analytics checks for a production environment to decide if it should add the tracking code.
When it comes to deploying to a staging environment this is problematic as you don't want to add the tracking code, but Gatsby forces the NODE_ENV to production. The same is true of Raygun, Hotjar, Facebook Pixel etc. The only solution is to set up duplicate properties for all of them and supply different ids to the tracking code for different environments.
Big down thumbs for not supporting "REACT_APP_" nor "GATSBY"... :(
Have there been any updates on this? Trying to get a staging environment going but looks like it's forcing NODE_ENV to be production
Most helpful comment
The problem here is that so many gatsby plugins use
process.env.NODE_ENV, for examplegatsby-plugin-analyticschecks for a production environment to decide if it should add the tracking code.When it comes to deploying to a staging environment this is problematic as you don't want to add the tracking code, but Gatsby forces the
NODE_ENVtoproduction. The same is true of Raygun, Hotjar, Facebook Pixel etc. The only solution is to set up duplicate properties for all of them and supply different ids to the tracking code for different environments.