How to use environment variables to implement functions in React projects?
P粉268284930
P粉268284930 2023-09-16 13:18:15
0
1
889

I'm trying to save my API key as an environment variable but I don't know how to access it... I installed dotenv using npm, created the file in the root directory and put the key there. I tried to access it in the js file by using process.env.API_KEY but it shows that the variable is undefined.

I tried putting require('dotenv').config() at the top of the file where I need the key, but it gives me an error...

ERROR in ./node_modules/dotenv/lib/main.js 2:13-28
Module not found: Error: Can't resolve 'path' in ...

I think I may have either put it in the wrong file or I'm missing something

P粉268284930
P粉268284930

reply all(1)
P粉014293738

in conclusion:

To read the API_KEY variable in your React layer you need to export the variable REACT_APP_API_KEY before building, then in any React part you can get the value via :

process.env.REACT_APP_API_KEY

See the link to see why the prefix REACT_APP_ is required.

Additionally, if your token is a long-lived or non-expirable token, it should not be exposed to the frontend (React). Only expirable tokens (AuthCodeoauth2Auth) should be exposed to the front-end layer.

Check out the references to learn how to handle front-end variables

References

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!