Home > Mobile >  Why my environment variable is not working in react
Why my environment variable is not working in react

Time:10-19

I want to hide my api key so i created .evn.local file in my react root directory and use process.env.API_KEY but it is sending undefined in the link instead of the actual api key

async componentDidMount() {
    const link = `https://newsapi.org/v2/top-headlines?category=${this.props.category}&pagesize=${this.props.pagesize}&country=${this.props.country}&page=${this.state.page}&apiKey=${process.env.API_KEY}`;
    const data = await fetch(link);
    this.setState({ loader: true });
    const final_data = await data.json();
    console.log(final_data);

.env.local file

API_KEY = apikey

CodePudding user response:

Try restarting the server. That might solve your problem.

CodePudding user response:

I think your app was created by using create-react-app.

If it is, there are a notice that the environment variables should be named with REACT_APP_ prefix.

Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

For more detail, please read this page of document.

CodePudding user response:

environment variables starting with REACT_APP_.

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

CodePudding user response:

In React project you have to use REACT_APP_ as a prefix in all the environment variables saved in .env* files in the root directory to use it. You can read more about it here: https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

  • Related