0

I'm making a client side React app and want to set an environment variable at runtime. My package.json contains

"scripts": {
    "start": "cross-env BUILD_TYPE=dev react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

and in my app I have

let api_base_url;
if (process.env.BUILD_TYPE === 'dev') {
  api_base_url = process.env.REACT_APP_API_DEV_SERVER_URL
  console.log("dev build");
} else {
  api_base_url = process.env.REACT_APP_API_SERVER_URL;
  console.log("not a dev build");
}

When I run my app using npm run start, first I see cross-env BUILD_TYPE=dev react-scripts start at the command line, then in the console I see not a dev build and it's using my non-dev server address. What am I doing wrong?

If it matters, I'm on Debian in WSL 2 on Windows 11.

JBallin
  • 8,481
  • 4
  • 46
  • 51
TrivialCase
  • 1,060
  • 2
  • 14
  • 27
  • 1
    https://create-react-app.dev/docs/adding-custom-environment-variables/ – JBallin Jul 14 '22 at 19:14
  • 1
    Prefix with `REACT_APP_` – JBallin Jul 14 '22 at 19:15
  • Use `process.env.NODE_ENV === 'development'` for this. – JBallin Jul 14 '22 at 19:16
  • Ah thanks - that was driving me nuts. Is there a reason I should prefer `NODE_ENV`? – TrivialCase Jul 14 '22 at 19:19
  • Does this answer your question? [create react app not picking up .env files?](https://stackoverflow.com/questions/48378337/create-react-app-not-picking-up-env-files) – JBallin Jul 14 '22 at 19:19
  • 1
    Just because it's set for you automatically by CRA (see linked docs), so why add unnecessary complexity of another env var? It's the standard way to do this. – JBallin Jul 14 '22 at 19:20
  • 2
    This doesn't make sense, you're baking both API URLs _and_ the thing which says which one to actually use in at build time. Just bake in one URL, or configure at runtime. – jonrsharpe Jul 14 '22 at 19:25
  • 1
    Good point. Check out [environment specific env files](https://create-react-app.dev/docs/adding-custom-environment-variables#what-other-env-files-can-be-used). That way you just reference `process.env.REACT_APP_API_URL` in your code, and depending on dev vs. prod it will pick up the right one automatically. – JBallin Jul 14 '22 at 19:32

0 Answers0