Can I have a different set of environment variables for deploy previews?

My app that I am deploying to Netlify uses Firebase. To keep things separate, I have two different Firebase apps - one for development and one for production. I configure which Firebase instance to use via environment variables.

I have seen how you can set environment variables for the deployed site, but I was wondering if it was possible to specify different environment variables for deploy previews? This way I can push a deploy preview via a pull request, and have that deployed instance talk to the Dev Firebase instance instead of the Prod instance.

Is this possible with Netlify?

Sure. You’ll want to use deploy contexts, as described here: File-based configuration | Netlify Docs

Then you can use some pattern like:

[build.environment]
  VAR = "default value unless specified by a context"
[context.deploy-preview.environment]
  VAR = "special deploy preview value"
[context.beta.environment]
  VAR = "value for all commits from the beta branch, or PR's targeting the beta branch"

Thanks for the reply.

If I understand it correctly, though, that would require checking the netlify.toml file into my Git repository, right? That would mean my API keys are checked in to source control where anybody can see them - is there any other way to do this?

Hey @joeattardi, that’s correct if you’re repo is public. There’s not a way to add env variables for different contexts in the UI. That said, I think this build plugin would accomplish what you want?

Plugins are available in your site UI here:

And here are docs on plugins:

One other thing you could try is using the netlify.toml as @fool described and setting different variables there equal to variables you set in the UI… I have no idea if that would work, but I think it would be something like this:

[build.environment]
  VAR = "default value unless specified by a context"
[context.deploy-preview.environment]
  VAR = process.env.KEY_YOU_ENTERED_IN_THE_UI

Let us know how it goes!

That wouldn’t work as Jen mentioned - you’d need to instead use those settings as a clue about which value to use. Something like this may work:

[build.environment]
  VAR = "DEFAULT"
[context.deploy-preview.environment]
  VAR = "DEPLOY_PREVIEW"

then in your build script, you could check $VAR and look for which “version” you want, and use variables set in our UI instead ($DEFAULT or $DEPLOY_PREVIEW). This lets you select a privately-set variable from a less-secure storage medium - at the cost of having to write a bit of logic to see what is set and dereference the correct variable to your needs.