Ryan Ferretti
Ryan Ferretti

Reputation: 2961

Heroku environment variables not set in javascript for React/Rails application

I've built a Rails-Api with React SPA frontend following this guide (very helpful, would recommend). I'm having issues getting Heroku to set the environment variables in the .env file that React uses for config vars. The values of the file are just set as literally "ENV[...]" instead of evaluating and setting the value. On the Rails side the Heroku ENV vars are being set correctly because I can see them in the console.

.env file:
REACT_APP_API_KEY=ENV['API_KEY']
REACT_APP_AUTH_DOMAIN=ENV['AUTH_DOMAIN']
App.js (top level Component):
console.log(config,process.env);
// which logs:
{
  NODE_ENV: "production"
  REACT_APP_API_KEY: "ENV['API_KEY']"
  REACT_APP_AUTH_DOMAIN: "ENV['AUTH_DOMAIN']"
  ...
}
Rails Console:
irb(main):001:0> ENV
=> {"LANG"=>"en_US.UTF-8", "NODE_ENV"=>"production",
"API_KEY"=>"<correct-value>", "AUTH_DOMAIN"=>"<correct-value>",......}

Is there something I need to do in order to alert Heroku that the ENV vars need to also be set in the .env file for the react app? The tutorial has the Heroku deployment use both the nodejs and ruby buildpacks (in that order). The app is built and then copied into the "public" dir for Rails to serve:

package.json
{
  //...
  "engines": {
    "node": "12.9.0",
    "yarn": "1.22.4"
  },
  "scripts": {
    "build": "yarn --cwd client install && yarn --cwd client build",
    "deploy": "cp -a client/build/. public/",
    "heroku-postbuild": "yarn build && yarn deploy"
  }
}

I don't know enough about the internal workings with Heroku's env vars swap. From what I understand with Create React App... the .env file's contents are set at build time so it is possible that the js is compiled before Heroku has any chance to inject the env vars. I'm open to suggestion on other ways to do this if this method isn't doable. Thanks!

Upvotes: 1

Views: 1410

Answers (1)

Petr Gazarov
Petr Gazarov

Reputation: 3821

You can expand environment variables in .env file. When React app is built, it has access to variables in your Heroku dyno, and react-scripts supports referencing them in your .env file. See more in docs.

With this in mind, your .env file would look like:

REACT_APP_API_KEY=$API_KEY
REACT_APP_AUTH_DOMAIN=$AUTH_DOMAIN

Assuming API_KEY and AUTH_DOMAIN variables are set in Heroku.

If you name these variables REACT_APP_API_KEY and REACT_APP_AUTH_DOMAIN in Heroku in the first place, then they will be picked up by react-scripts directly from the environment (no need for .env file then)

NOTE: with the above said, it sounds like you are trying to expose secrets in React app. The Create React App docs strongly warns NOT to do that, because:

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

Upvotes: 2

Related Questions