Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
61 views
in Technique[技术] by (71.8m points)

javascript - 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.

question from:https://stackoverflow.com/questions/65905397/hiding-the-api-key-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...