Home > database >  Deploying a react application on an s3 bucket with multiple environments
Deploying a react application on an s3 bucket with multiple environments

Time:11-08

I'm using heroku to deploy a nodejs backend, and amazon s3 to deploy the static files of a react app, so the frontend stored on an s3 bucket makes requests to the heroku backend.

Once I finished creating my staging environment for heroku, I just needed to create a new bucket and hook up the new url so the staging frontend can correctly make requests to the staging backend, I ended up with something like this on my react app:

// index.js
let BASE_API_URL;

if (process.env.NODE_ENV === "production") {
  BASE_API_URL = "https://myproductionapiurl.com";
else if (process.env.NODE_ENV === "staging") {
  BASE_API_URL = "https://mystagingapiurl.s3-website.us-east-2.amazonaws.com";
} else {
  BASE_API_URL = "https://someotherurl.com";
}

axios.defaults.baseURL = BASE_API_URL;

But then I noticed that s3, being a service to save your static files, doesn't have a way to set environment variables, so I can't specify based on process.env.NODE_ENV to what url to make the requests, and I got stuck.

Right now I'm just hard coding the url so it works, but once I try to merge the staging and production environments a git conflict will always appear, is there any way I can do this using amazon s3 buckets and react?

CodePudding user response:

Thanks to @jonrsharpe I was able to get it working, since I'm using react, instead of using NODE_ENV (which cannot be overwritten) I used REACT_APP_ENV, and I set it as an environment variable before running the build:

REACT_APP_ENV=staging npm run build

  • Related