如何在AWS EC2中为React&Go设置环境变量

如何在AWS EC2中为React&Go设置环境变量

问题描述:

I've made React & Go product in local. And I'm going to deploy it to AWS EC2.

To work in AWS EC2, I need to set environment variables for some secret information.

I've already set env variables for local environment. But I'm not sure about env variables working for production environment(AWS EC2).

I already set env. file for local environment. But not sure how to set environment variables in ec2.

I use environment variables for axios, firebase and mysql.

//axios
   const client = axios.create({
      baseURL: process.env.REACT_APP_API_URL,
    });
    client
      .get('/api/articles')
      .then(response => {
        this.setState({articles: response.data});
      })
      .catch(response => console.log('ERROR!! occurred in Backend.'));
//firebases
const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: '',
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
};

firebase.initializeApp(firebaseConfig);

export default firebase;
//mysql
    err := godotenv.Load()
    if err != nil {
        //TODO production

    }
    db, err := sql.Open("mysql", os.Getenv("MYSQL_USER")+":"+os.Getenv("MYSQL_PASSWORD")+"@tcp(localhost:3306)/article")
    if err != nil {
        panic(err.Error())
    }

    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

Here is the github. https://github.com/jpskgc/article

I'm going to deploy this React & Golang product in AWS EC2. But I'm not sure how to set environment variables.

I use elastic beanstalk and set environment variables there.

In the shell script you are using to launch your server on EC2, add the environment variable definition, for example :

export ENV_VAR_1=value_1
export ENV_VAR_2=value_2

... start your server ...

Note that this will only work for the server side. The React App is made of Javascript running in the client's browser and you can not control the environment variables there.

If I understand well, the Axios code extract above is part of the React front end. You can not have process.env there as this is executed on customer machine.