简体   繁体   中英

Setting environment variables in a shell script for a React app

I am trying to set some environment variables in a powershell (and bash) script and read them in a ReactJS application. The shell script is simple:

$env:AUTHDOMAIN="some.domain.com"
$env:AUTHCLIENTID="bunch-o-characters"
$env:AUTHCALLBACK="http://somewhere:3002/callback"
$env:AUTHAUDIENCE="auth-audience"

$env:PORT=3002

# Get-ChildItem Env:

yarn start

The port is being picked up correctly by yarn but none of the variables (including PORT ) are available via process.env within the React javascript.

console.log("domain     : " + process.env.AUTHDOMAIN);
...
domain     : undefined App.js:33

No mods to my package.json file:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

What am I missing? Get-ChildItem shows that the variables are set correctly in the environment.

Edit: I tried the solution listed here and it doesn't work. It also blocks the terminal from receiving any output:

$ ($env:AUTHDOMAIN="some.domain.com") -and (yarn start)

Same result.

Edit #2: It's worth noting that the behavior is exactly the same in linux/bash (which is a good litmus test cuz I've done this in bash about a 100 billion times) - yarn sets the port correctly but none of the info makes it into the react app:

#!/bin/sh

export AUTHDOMAIN="some.domain.com"
export AUTHCLIENTID="bunch-o-text"
export AUTHCALLBACK="http://somewhere:3001/callback"
export AUTHAUDIENCE="auth-audience"

export PORT=3002

yarn start

So this likely has nothing to do with powershell.

Every environment variable you wish to consume must be prefixed with REACT_APP_ as per the documentation of create-react-app :

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

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