Environment Variables by context

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:

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:


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?


According to the documentation here: https://docs.netlify.com/configure-builds/environment-variables/#declare-variables 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:

	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