0

I'm trying to deploy my react app using Netlify, which uses a secret token for an API I'm using on the front-end. I defined the token in process.env with webpack to do this.

Problem:

After the Netlify deployment, my app returns a "NO_TOKEN_WARNING" error.

It works when bundling locally, which tells me I might be setting up the environment var incorrectly in Netlify?

My setup:

  • For prod, I manually entered the API token into Netlify's "environment setup" page (Build & Deploy > Environment > Environment Variables") - I tried enclosing the token with & without quotes.
  • I am not using creat-react-app - I created my own webpack file from scratch. I realize you could use react-scripts for create-react-app, but that isn't the case for me.
  • For dev, I'm using webpack.DefinePlugin to set the environment variable for the token, which gets the actual token value from a .gitignore'd file.

Note: I'm using webpack-merge separate my webpack config files into 3: webpack-common, dev, and prod.

webpack.dev.js:

...
const config = require('./config.js'); // importing the file with the token

module.exports = merge(common, {
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './client/dist',
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env.SECRET_TOKEN": JSON.stringify(config.SECRET_TOKEN), // token is here
    })
  ],
})

config.js:

module.exports = { SECRET_TOKEN: 'super secret' };
tbd_
  • 1,058
  • 1
  • 16
  • 39
  • 1
    Does this answer your question? [Set environment variable for build in Netlify](https://stackoverflow.com/questions/48453493/set-environment-variable-for-build-in-netlify) – JBallin Dec 29 '19 at 06:27
  • 1
    Netlify discussion: https://community.netlify.com/t/common-issue-using-environment-variables-on-netlify-correctly/267 – JBallin Dec 29 '19 at 06:30
  • Can you explain where/how you’re getting the token from netlify’s env vars? I’m assuming webpack.dev isn’t called in prod. Are you just making an assumption that netlify automatically stores vars in process.env? – JBallin Dec 29 '19 at 06:34
  • 1
    Note that you shouldn’t even be storing secrets on the front end, so really this work is futile - but there are use cases for env specific non-secret vars. – JBallin Dec 29 '19 at 06:35
  • @JBallin I got it working! I followed the instructions on the duplicate question in your first comment using dotenv-webpack and the create-env script. I'm guessing that still having your token in Netlify's environment variable is not safe? In any case, thank you! – tbd_ Dec 29 '19 at 07:51
  • 1
    Great! The issue isn’t that it’s on Netlify’s servers, it’s that anyone can see the token in their browser when making a request on your site in the network requests/source code. Ideally you’d have a separate backend that stores the secret and handles calling the external API. – JBallin Dec 29 '19 at 08:08

0 Answers0