What's the proper way of setting environment variables in netlify? I would like to be able to set different values for the variables depending on the environment.
Pseudo code:
let host;
if (process.env.GATSBY_CUSTOM_CONTEXT === 'production') {
host = process.env.PRODUCTION_HOST
} else if (process.env.GATSBY_CUSTOM_CONTEXT === 'development') {
host = process.env.DEVELOPMENT_HOST
}
I have tried passing env variable thru CLI, like GATSBY_CUSTOM_CONTEXT=production gatsby build and I also tried using same command with cross-env.
My other attempt used netlify.toml:
[build]
base = "/"
publish = "public"
command = "yarn build"
functions = "src/functions"
[context.production]
[context.production.environment]
GATSBY_CUSTOM_CONTEXT = "production"
All of these options worked with netlify dev locally, but in production GATSBY_CUSTOM_CONTEXT is always undefined.
P.S.
Not sure if I used the right repo to post this question. Feel free to tell me if this issue has to be moved some other place. I have also asked this question in https://github.com/netlify/ask-netlify/issues/59 bc I would like to see a more in-depth tutorial.
you're not alone. this is the top question https://github.com/netlify/netlify-dev-plugin/issues/114 cc @raeesbhatti
for your case, since you have env vars working locally, then the only thing left to do is to set them for your production environment here https://www.netlify.com/docs/continuous-deployment/#environment-variables
https://app.netlify.com/sites/YOURSITEHERE/settings/deploys#environment

Is there no way to differentiate between running netlify dev locally and my function running in production on Netlify? If I set an environment variable in the Netlify control panel, I can't override it on my local machine (or I haven't figured out how). In my case, I'm trying to use a different GitHub auth client id/secret in development and production.
Edit: I discovered the NETLIFY_DEV environment variable that allows me to make the distinction I was talking about in my original comment. Hooray! 馃帀
Does this help in your situation @iamskok?
const {
NETLIFY_DEV,
GITHUB_CLIENT_ID_DEV,
GITHUB_CLIENT_ID_PROD
} = process.env;
const response = await axios.post('github api url', {
client_id: NETLIFY_DEV
? GITHUB_CLIENT_ID_DEV
: GITHUB_CLIENT_ID_PROD
});
@trevorblades thanks for updating your answer! This should solve my problem.
Most helpful comment
Is there no way to differentiate between runningnetlify devlocally and my function running in production on Netlify? If I set an environment variable in the Netlify control panel, I can't override it on my local machine (or I haven't figured out how). In my case, I'm trying to use a different GitHub auth client id/secret in development and production.Edit: I discovered the
NETLIFY_DEVenvironment variable that allows me to make the distinction I was talking about in my original comment. Hooray! 馃帀Does this help in your situation @iamskok?