简体   繁体   中英

How do I use Netlify's environment variables in JavaScript?

I want to use an environment variable to store Google Analytics tracking ID for a project. I've created an environment variable on Netlify named 'GOOGLE_ANALYTICS_ID'. I want to use this variable in my JavaScript file to replace the actual tracking ID.

Right now, all I'm doing is using 'GOOGLE_ANALYTICS_ID' as is to call the variable. It's showing a Reference Error in my console.

What's the correct way of doing this? I just want the tracking ID number in the JS file to be replaced with the environment variable name so it gets the value from Netlify rather than hardcoding it in the file.

您应该使用process.env.GOOGLE_ANALYTICS_ID引用 env var。

In Netlify

  1. Login in to netlify: https://app.netlify.com/teams/USERNAME/sites
  2. Pick your site: https://app.netlify.com/sites/SITENAME/overview
  3. Go to site settings: https://app.netlify.com/sites/SITENAME/settings/general
  4. Go to "Build & Deploy" > "Environment variables": https://app.netlify.com/sites/SITENAME/settings/deploys#environment
  5. Edit variables:
    • Key: GOOGLE_ANALYTICS_ID
    • Value: UA-XXXXXXX-X
  6. Save

I had some problems getting analytics to work in GatsbyJS. There are some caveats:

If you are using Gatsby: In gatsby-config.js

  plugins: [
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: GOOGLE_ANALYTICS_ID,
        head: true,
        anonymize: true,
      },
    },
  ]

Attention: gatsby-plugin-google-analytics is only enabled with gatsby build command

This means you cannot test tracking during local development with gatsby develop .

From the plugin docs :

Note that this plugin is disabled while running gatsby develop . This way, actions are not tracked while you are still developing your project. Once you run gatsby build the plugin is enabled. Test it with gatsby serve .

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