Use, Access & Share Environment Variables on Netlify

Phil Hawksworth - Dec 10 '21 - - Dev Community

Throughout December we'll be highlighting a different Netlify feature each day. It might just be the thing you need to unlock those creative juices, and dust off that domain you registered but never deployed! Keep an eye on the blog and on Twitter for each feature!

Netlify allows you to create and access build environment variables in a secure, and private location in your project's dashboard. Site settings > Build & deploy > Environment > Environment variables, to be exact, ooh or Team settings > Sites > Global site settings > Shared environment variables if you're the "sharing is caring" type.

Configuring environment variables in the Netlify admin app

These can also be set using the Netlify configuration file, netlify.toml. On top of that, you can even inject those environment variables into any shell command (such as the [build] command and ignore command). Here's more info on that and here's what that would look like.

# netlify.toml

[build]
  command = "cp ./ ${PROJECT_COPY_DIR} && npm run build"
  publish = "dist/my-project"
  environment = { 
    PROJECT_COPY_DIR = "/that/one/place",
    GO_IMPORT_PATH = "go/go/gadget.go",
    API_KEY = "abc1234teeheehee"
  }

[context.staging] # “staging” is a branch name
  command = "npm run dev"
  base = "staging"
  environment = { SOME_KEY = "t0te5Important5tuff" }
Enter fullscreen mode Exit fullscreen mode

You can set different environment variables for different deploy contexts and access them through your serverless functions, snippet injection, app code (I tend to grab them via process.env.THIS_ENV_VAR_NAME in my code), and many other ways. If you have team members you are onboarding don't worry about giving them the project env vars insecurely over slack or through multiple steps of auth, they just live with the project.

You can learn a bunch more through our docs. There is all kinds of fun stuff there including a bunch of environment variables that tell you things like build metadata, git metdata, build hook meta data (& payload), deploy URLS and MORE metadata!

Hope this helps you keep things available to your nice devs and away from naughty hackers. Happy coding 👩🏻‍💻!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .