I'm using React 16.12.0. I have the following "proxy" configured in my package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.4.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.3.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"proxy": "http://localhost:9090",
This works great for development, but when I move my site to qa and production, I would like the ability to have my package.json file read from an environment variable of some kind. How do I write my package.json or configure my app to use a different URL based on the environment, or at least a variable set in my environment?
By using dotenv and cross-var together, we're able to read in whichever . env files we want, or consume existing environment variables (from cli, bash_profile, CI, etc) and then easily substitute them into our package. json scripts and it works across development platforms!
On the Advanced tab, click Environment Variables. Click New to create a new environment variable. Click Edit to modify an existing environment variable. After creating or modifying the environment variable, click Apply and then OK to have the change take effect.
On the Projects page, select the project that you want to import environment variables to, and click Properties to open the Project Properties window. On the General page, click Environment. In the Environment Variables dialog, click Import from File.
cross-env makes it so you can have a single command without worrying about setting or using the environment variable properly for the platform. Just set it like you would if it's running on a POSIX system, and cross-env will take care of setting it properly. Installation. Usage.
From the docs: https://create-react-app.dev/docs/proxying-api-requests-in-development/
Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.
As an alternative, you can use environment variables instead: https://create-react-app.dev/docs/adding-custom-environment-variables/
You should create .env.development
and .env.production
files at the root of your project:
# .env.development
REACT_APP_PROXY=http://localhost:9090
# .env.production
REACT_APP_PROXY=<some other domain>
And consume it on the react app:
// anywhere in the react app
const REACT_APP_PROXY = process.env.REACT_APP_PROXY
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With