I can not access my environment variables in netlify

Viewed 2091

I code an app with Gatsby and Netlify.

I am using Snipcart public API key via environment variables in my html.js (to have test key in dev and live key in prod).

import React from 'react'
import PropTypes from 'prop-types'

export default class HTML extends React.Component {
  render() {
    return (
      <html lang='en' {...this.props.htmlAttributes}>
        <head>
          <meta charSet='utf-8' />
          <meta httpEquiv='x-ua-compatible' content='ie=edge' />
          <meta
            name='viewport'
            content='width=device-width, initial-scale=1, shrink-to-fit=no'
          />
          {this.props.headComponents}

          {/* Snipcart */}
          <script
            defer
            src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js'
          />
          <script
            defer
            src='https://cdn.snipcart.com/scripts/2.0/snipcart.js'
            id='snipcart'
            data-api-key={process.env.SNIPCART_API_KEY}
          />
          <link
            href='https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css'
            type='text/css'
            rel='stylesheet'
          />
        </head>
        <body {...this.props.bodyAttributes}>
          {this.props.preBodyComponents}
          <div
            key={'body'}
            id='___gatsby'
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
        </body>
      </html>
    )
  }
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array
}

Locally everything works with my .env.development and env.production.

When I build and serve the app locally I have no problem. The variables are correct when I call :

process.env.SNIPCART_API_KEY

In Netlify I indicated in the build parameters my production variable:

SNIPCART_API_KEY = PROD_VALUE

But when the site is deploying the variable is not taken into account. (.env files are in .gitignore)

I think I did something wrong in the Netlify settings but I do not know what.

How to access this variable once the site deploys?

1 Answers
Related