How to access $PORT environment variable in React App on Heroku

Viewed 2145

I am running a server and a React site on the same Heroku app. My server.js is able to access the $PORT environment variable fine, but my React app is not getting anything from it (the variable is blank).

I need to be able to access the PORT environment variable because thats what my server (Radiks) is running on. From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.

My Procfile:

web: REACT_APP_PORT=$PORT node src/server.js

In package.json:

...
"scripts": {
    "start": "node server.js",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install && npm run build",
    "build": "REACT_APP_PORT=$PORT react-scripts build",
    "test": "react-scripts build",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
...

In my React app (App.js):

...
console.log("Connected to server:" + process.env.REACT_APP_PORT);
configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession})
...

(This ends up only printing out Connected to server:)

Any help would be greatly appreciated, thank you in advance!

1 Answers

From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.

That's new to me. I looked it up and also saw the passage that said this so I'm going to take your word for it.

web: REACT_APP_PORT=$PORT node src/server.js

Seems plausible.

"build": "REACT_APP_PORT=$PORT react-scripts build",

You are building your html, js, css files here. The port is never used. Heroku's $PORT value is dynamic. It changes from time to time. So when you are building your static files it still references a variable instead of a hardcoded value.

configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession}

Should be:

configure({ apiServer: "http://localhost:" + process.env.PORT || process.env.REACT_APP_PORT || 1260, userSession}

Just in case $PORT works I put it in there. If it does not exist it will pick $REACT_APP_PORT.
Your previous code was missing protocol and host.

Related