简体   繁体   中英

Printing environment variables on console but getting undefined

I have a.env file that has my API keys and I want to print them on the console. I am following this tutorial https://medium.com/better-programming/using-environment-variables-in-reactjs-9ad9c5322408 . This doesn't work for me, my API key values don't get printed on console and instead undefined gets printed.

my.env file

S3_BUCKET_NAME=petition-form
AWS_ACCESS_KEY_ID=-----------------
AWS_SECRET_ACCESS_KEY=---------
AWS_REGION=us-east-2
REACT_APP_CLIENT_ID=jfjffffaddfeettgydgdffv

my app.js file

import React from "react";

const App = () => {
  console.log(process.env.S3_BUCKET_NAME);
  console.log("adib");
  console.log(process.env.REACT_APP_CLIENT_ID);
  return <h1>Hello</h1>;
};

export default App;



Dotenv only works server-side. In this case dotenv needs some sort of environment to actually store the variables. Something like Webpack. Read this article for more info on using environment variables in React. https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5

You can't hide the API_KEY on client side. The browser would compile all of your code and finally your API_KEY would be published.

In my opinion, you would integrate that API on backend and then you would just simply call your own backend API. That is the best way to hide your API_KEY.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM