1

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.

8
  • 1
    create-react-app.dev/docs/adding-custom-environment-variables Commented Jul 14, 2022 at 19:14
  • 1
    Prefix with REACT_APP_ Commented Jul 14, 2022 at 19:15
  • 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. Commented Jul 14, 2022 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. Commented Jul 14, 2022 at 19:25
  • 1
    Good point. Check out environment specific env files. 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. Commented Jul 14, 2022 at 19:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.