Hi guys, I have a problem with my environment variables. I’m currently using a plugin called ‘netlify-plugin-contextual-env’ and it changes the env vars like this: SEND_GRID_KEY becomes STAGING_SEND_GRID_KEY and PRODUCTION_SEND_GRID_KEY accordingly.
Then in my function am using it like this
const sendGridKey = process.env.SEND_GRID_KEY
In my netlify build and deploy settings I have the following keys:
SEND_GRID_KEY
STAGING_SEND_GRID_KEY
PRODUCTION_SEND_GRID_KEY
However, my function always refers to the value of SEND_GRID_KEY
Do I still need a conditional like this:
let sendGridKey;
if (context === "production") {
sendGridKey = process.env.SEND_GRID_KEY
} else if (context === "deploy-preview" || context === "branch-deploy") {
sendGridKey = process.env.STAGING_SEND_GRID_KEY
}
If so, why do we need the plugin in the first place?
Please let me know if where is my error when using the plugin.
Thank you!
You can add this to netlify.toml
:
[context.production.environment]
SEND_GRID_KEY = "A"
[context.deploy-preview.environment]
SEND_GRID_KEY = "B"
Then you won’t need to create 2 EVs like SEND_GRID_KEY and STAGING_SEND_GRID_KEY.
Hi Hrishikesh, thank you for your answer.
if I do that I would expose my env vars since the netlify.toml file needs to be pushed to the repo.
Do you have any other alternative to approach this?
Cheers!
According to the documentation here: Build environment variables | Netlify Docs the contextual config is only available in TOML file. So, my guess would be, there is no other way.
However, you can at least set the context by using:
[build]
context = "production"
Hi @moiscye, it’s been awhile since you reached out about setting different environment variable values to different deploy contexts. If this is still relevant for you, though, we’ve released the “Scopes and deploy contexts for environment variables” beta in Labs. This beta will enable you to set contextual values from the Netlify UI, CLI, or API. Hope that helps and happy to hear any feedback you may have!
1 Like