简体   繁体   中英

What's the proper way of setting environment variable in Netlify functions?

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 .

The reason you can't resolve the environment variables in your Netlify functions is because as of the time of your question, Netlify does not transfer the environment variables from the netlify.toml file.

You must put them into the admin panel in your site settings in the app.netlify.com dashboard.

Unfortunately, what you're looking to doesn't seem to be currently supported. Though they provide an alternative approach.

I found this snippet on their docs:

CALLING ENVIRONMENT VARIABLES

Using environment variables directly as values ($VARIABLENAME) in your netlify.toml file is not supported. However, the following workflow can be used to substitute values in the file with environment variable values, assuming you are only trying to change headers or redirects. The rest of the file is read BEFORE your build — but those sections are read AFTER the build process.

  1. Add a placeholder like HEADER_PLACEHOLDER somewhere in the netlify.toml redirects or headers sections.
  2. Create an environment variable, for example PROD_API_LOCATION, with the desired value. You can create environment variables in the toml file or in our UI. You might use the latter to keep sensitive values out of your repository.
  3. Prepend a replacement command to your build command. Here's an example for a site using yarn build to build: sed -is/HEADER_PLACEHOLDER/${PROD_API_LOCATION}/g netlify.toml && yarn build

Taken from here: https://www.netlify.com/docs/netlify-toml-reference/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM