Kalvin
Kalvin

Reputation: 13

Hiding the API key in React

We have an application that uses an API key (Accesstoken). We would like to hide the API key in a .env file.

We have gone through the following steps.

  1. Created a .env file in the source folder (with the .gitignore)

  2. Added in the .env REACT_APP_ACCESSTOKEN = pk.ffe1Ijo.......

  3. In the terminal added the npm install dotenv

  4. Added the into our map.component file - import dotenv from 'dotenv' dotenv.config() const accessToken = process.env.REACT_APP_ACCESSTOKEN;

  5. Added to webpack.config.js -

    externals: ["fs"], resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },

Now we get the error message in the web browser console that fs is undefined. Or that the Acesstoken is not found.

Upvotes: 1

Views: 1454

Answers (1)

Nicky Logan
Nicky Logan

Reputation: 120

As per the create-react-app documentation, unless you're creating toy apps, it's not a good idea to store secret keys in your React app.

But, in case you really need to:

If you're using create-react-app, there's no need to install a separate dotenv library, as it's supported out of the box.

Otherwise, dotenv-webpack is probably something you can try. See this other SO question.

Upvotes: 1

Related Questions