[Support Guide] Using environment variables on Netlify correctly

Heh, that’s how I found my way here @fool :smiley:

Thanks for explaining @fool – that’s really interesting, and unexpected! I’ve confirmed now that when I allow the builds to having via github webhooks (eg, branch deploys or master updates) then the prefixed GATSBY_ magic substitution happen as expected.

Is there a way I can leverage the Netlify CI builds when using netlify deploy to test deploys of WIP code? I guess I expected this would work because I have a build command defined in my netlify.toml which leads to a gatsby build, but now I think this may be irrelevant.

edit: Hmm as an update, I’ve discovered that process.env.DEPLOY_URL is undefined in a PR preview deploy, from the context of a function. Hmm this I’m less sure how to work around.

Well, yes, you can follow the pattern in this article. Sorry to sound like a broken record, but if you want a single workflow for both places:

  1. DON’T use GATSBY_*, use non-special environment variables

  2. that you must manually interpolate,

  3. and do that both locally (set on your machine) and at Netlify (set in our UI).

I’m using Gatsby and know that my build command is gatsby build. I’ve declared my variables in the Netlify UI so I don’t really care about confirming they are showing up in my console or how to do that.

What I would like is to fix the problem of my environmental variables showing undefined after I’ve built and deployed my site.

I understand that build time and run time are two different animals: that build time is basically distilling and packaging all your pages and their dependencies/assets into files that can be digested by the browser; run time being what the browser does with those files, functions/directives, etc., and that the environmental variables need to baked into the code so that the browser has access to it and so that it is not undefined.

That now has me wondering if that isn’t inherently a security concern?

I guess what I’m really wondering is if there’s an alternative to using Netlify’s serverless functions to run code that uses predeclared environmental variables?

Does anybody know of an alternative to this?

I just built a netlify build plugin https://github.com/bencao/netlify-plugin-inline-functions-env to hopefully support most typical use cases by inlining process.env.X in function js files with build time environment variable values.

2 Likes

@bencao’s plugin is a great way to automate this! But your concerns are well placed - if you can’t share your environment variables with the general public in your page source code, you absolutely don’t want to publish them here!

This is a function that demonstrates how to “hide” sensitive tokens - such as credentials: https://github.com/depadiernos/token-hider-inator . Some authentication tokens - e.g. firebase read or write tokens - are intended to be in webpages. Most, though, are not, so it is very wise to be concerned!