umer
umer

Reputation: 1316

Passing Environment variables to React application from Package.json

following this article https://serverless-stack.com/chapters/environments-in-create-react-app.html

I am trying to add an environment variable to my react app which I have created using create react app. so my build command looks like below

 "build": "REACT_APP_SECRET_CODE=123 react-scripts build",

while I try to run this build command in my Visual studio code terminal via

npm run build 

it gives me the error that REACT_APP_SECRET_CODE is not recognized as an internal or external command.

How would i pass the environment variable in `package.json and build my app and access the variable value in my app.

Upvotes: 3

Views: 4548

Answers (2)

akzarma
akzarma

Reputation: 189

If you don't want to install any other library. You can pass environment variable to yarn or npm command like this:

"scripts": {
 "start": "breact-scripts start",
 "start:env": "REACT_APP_ABC=xyz yarn start",
}

Note: Remember to put prefix "REACT_APP_" in your environment variable otherwise React won't allow it to use in app.

Upvotes: 1

Jee Mok
Jee Mok

Reputation: 6556

you can do it in a clean way (imo) using better-npm-run package

{
  "devDependencies": {
    "better-npm-run": "~0.0.1"
  },
  "scripts": {
    "build": "better-npm-run build",
  },
  "betterScripts": {
    "build": {
      "command": "react-scripts build",
      "env": {
        "REACT_APP_SECRET_CODE": "123"
      }
    }
  }
}

there are more advanced usage for this library, which I think might help you in the long term on your project

Upvotes: 0

Related Questions