Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass GATSBY* environment variables into app #660

Closed
danielres opened this issue Feb 7, 2017 · 22 comments · Fixed by #1462
Closed

Pass GATSBY* environment variables into app #660

danielres opened this issue Feb 7, 2017 · 22 comments · Fixed by #1462
Labels
type: question or discussion Issue discussing or asking a question about Gatsby

Comments

@danielres
Copy link
Contributor

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

@KyleAMathews
Copy link
Contributor

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.

config.plugin('define', webpack.DefinePlugin, [{

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

@danielres
Copy link
Contributor Author

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.

@KyleAMathews
Copy link
Contributor

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?

@KyleAMathews KyleAMathews reopened this Feb 8, 2017
@danielres
Copy link
Contributor Author

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 ! 👍 :)

@danielres
Copy link
Contributor Author

danielres commented Feb 9, 2017

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_ ?

@KyleAMathews
Copy link
Contributor

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 😄 ).

@corderophilosophy
Copy link

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.

@oliverbenns
Copy link
Contributor

oliverbenns commented Feb 15, 2017

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.

@KyleAMathews
Copy link
Contributor

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?

@KyleAMathews KyleAMathews changed the title can't set environment variables Pass GATSBY* environment variables into app May 24, 2017
@KyleAMathews
Copy link
Contributor

@0x80 had a good idea that for v1 we could also provide an action creator for directly setting environment variables #1033 (comment)

@liorix
Copy link

liorix commented Jul 12, 2017

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
}

@lleger
Copy link

lleger commented Sep 4, 2017

@KyleAMathews I’m not sure #1462 fully addressed this since there’s still no way to pass in true ENV vars without adding a file. This precludes e.g. using Netlify’s built-in ENV var management.

@KyleAMathews
Copy link
Contributor

Right #1462 (comment)

Would love a PR from you adding support for this!

@quentin-
Copy link

quentin- commented Jan 29, 2018

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;
}, {});

@fk fk added the type: question or discussion Issue discussing or asking a question about Gatsby label Jan 29, 2018
@KyleAMathews
Copy link
Contributor

@quentin- did you see this page? We do support .env.production files

https://www.gatsbyjs.org/docs/environment-variables/

@KyleAMathews
Copy link
Contributor

Not sure if what you're proposing is different. If it is, please post a new issue to track the discussion there!

@HuuDuc
Copy link

HuuDuc commented Jan 31, 2018

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?

@KyleAMathews
Copy link
Contributor

@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.

@designbyadrian
Copy link

designbyadrian commented Feb 15, 2018

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

@Undistraction
Copy link
Contributor

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.

@JimLynchCodes
Copy link
Contributor

JimLynchCodes commented Sep 1, 2019

Big down thumbs for not supporting "REACT_APP_" nor "GATSBY"... :(

@erosenberg
Copy link

erosenberg commented Oct 8, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question or discussion Issue discussing or asking a question about Gatsby
Projects
None yet
Development

Successfully merging a pull request may close this issue.