Using environment variable in create-react-app package.json proxy - reactjs

I would like to set the "proxy"-property in the package.json file of a create-react-app project to the value of an environment variable called "REACT_APP_API_BASE_URL". The variable is stored in the .env.development.local file. I can't find the right way to do this. What is the right notation to access the variable? Each way I tried ended in the following error, when starting the app with npm start:
When "proxy" is specified in package.json it must start with either http:// or https://
This error probably occurred because the value isn't accessed correct.

If you specify in your .env.development.local:
REACT_APP_API_BASE_URL=[your url]
you can use source .env.development.local to store the value and then use it using $REACT_APP_API_BASE_URL.
For example in your package.json you could do this:
"scripts": {
"deploy": "react-scripts build; source .env; ./scripts/deploy.sh $REACT_APP_API_BASE_URL"
}

Related

How to setup local environment to run on https

I am trying to run my React application via https local. I have followed the steps of this tutorial, have installed mkcert correctly and the root of my project currently looks like this:
|-- my-react-app
|-- package.json
|-- localhost.pem
|-- localhost-key.pem
|--...
And my package.json file looks like this:
"scripts": {
"start": "HTTPS=true SSL_CRT_FILE=localhost.pem SSL_KEY_FILE=localhost-key.pem react-scripts start",
...
Yet when I run npm start I receive this error:
'HTTPS' is not recognized as an internal or external command, operable program or batch file.
I also tried creating a .env file in the root and adding the variables like this:
HTTPS=true
SSL_CERT_FILE=localhost.pem
SSL_KEY_FILE=localhost-key.pem
However when I run the app this way I receive a warning to say my connection is not secure.
I have spent time googling the errors and so far still unable to find a solution.
The solution was to amend my package.json file to look like this:
"scripts": {
"start": "set HTTPS=true&&set SSL_CRT_FILE=localhost.pem&&set SSL_KEY_FILE=localhost-key.pem&&react-scripts start",
...
This produced a RangeError: Invalid typed array length: -4095 on start. Upgrading my react scripts to the latest version with npm install --save react-scripts#latest solved that.
I now have a secure connection on my localhost. Hope this helps someone else out in the future.

How do I use environment variables or mask secrets in package.json?

Here's an excerpt from my package.json file:
"scripts": {
"start": "cross-env NODE_ENV=prod npx ./bin/www",
"migrate": "node-pg-migrate",
"migrate_dev": "DATABASE_URL=postgres://username:password#localhost:5432/dev_db NODE_ENV=dev node-pg-migrate",
},
I'm excluding my .env file in .gitignore to ensure my secrets don't leak into the git repo. What I want to know is, what's the best way to deal with the username:password part of the migrate_dev script?
(And I've taken a look at this, but I'm pretty sure I can't use a .js file as a package.json stand-in.)
I tried assigning environment variables to environment variables, e.g.
"scripts": {
...
"migrate_dev": "DATABASE_URL=DEV_DB_URL NODE_ENV=dev node-pg-migrate",
...
},
but, sadly they aren't defined at this point - #bootstraps! ;-)
How do I use environment variables or mask secrets in package.json?
I'm excluding my .env file in .gitignore to ensure my secrets don't leak into the git repo.
Because your secrets are in your .env file, they can only be accessed programmatically, and package.json does not have that capability on its own. This would require a .js file.
You can run a .js file (i.e. migrate_dev.js) from your migrate_dev script:
"migrate_dev": "node migrate_dev.js"
Inside migrate_dev.js you should have access to your.env file and node-pg-migrate's Programmatic API (its CLI equivalent for JS):
https://salsita.github.io/node-pg-migrate/#/api

dotenv : how to set custom path

This is my architecture and I want to access the.env file
I tried all the solutions, __dirname, find-config, ckey and read all the stack solutions. I can't understand why my .env file is not loaded....
console output is always :
{NODE_ENV: "development", PUBLIC_URL: ""}
If you're using create-react-app to bootstrap your application, the react-scripts module handles setting up environment variables for you. However, there's a catch. All React environment variable needs to be prefixed with REACT_APP. Thus, your environment variable would be: REACT_APP_MY_ENV_VARIABLE.
You should not import dotenv. After changing .env files, you must restart the development server. This is the excerpt from the create-react-app docs. The .env must appear in the root of your project.
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.
You can read more about environment variables and .env files with create-react-app in the create-react-app documentation.
If you really need to set a custom path, you can use env-cmd. It requires small changes in scripts section like this:
// from
"start": "react-scripts start"
// to
"start": "env-cmd -f ./custom/path/.env react-scripts start"

create react app not picking up .env files?

I am using create react app to bootstrap my app.
I have added two .env files .env.development and .env.production in the root.
My .env.development includes:
API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback
When I run my app using react-scripts start and console out process.env it spits out
{ NODE_ENV: "development", PUBLIC_URL: "" }
I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!
Directry structure is:
/.env.development
/src/index.js
Package.json script is:
"start": "export PORT=3005; npm-run-all --parallel server:start client:start",
"client:start": "export PORT=3005; react-scripts start",
"server:start": "node server.js",
"build": "react-scripts build",
Edit:
#jamcreencia correctly pointed out my variables should be prefixed with REACT_APP.
Edit 2
It works okay if I name the file .env but not if I use .env.development or .end.production
With create react app, you need to prefix REACT_APP_ to the variable name. ex:
REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_CALLBACK_URL=http://localhost:3005/callback
** Make sure your .env file is in the root directory, not inside src folder.
CRA Docs on Adding Custom Environment Variables:
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
Make sure your .env file is in the root directory, not inside src folder.
Had this same problem! The solution was to close the connection to my node server (you can do this with CTRL + C). Then re-start your server with 'npm run start' and .env should work properly.
Source: Github
If you want to use multiple environment like .env.development .env.production
use dotenv-cli package
add .env.development and .env.production in project root folder
and your package.json
"scripts": {
"start": "react-app-rewired start",
"build-dev": "dotenv -e .env.development react-app-rewired build",
"build-prod": "dotenv -e .env.production react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
then build according to environment like
npm run-script build-dev
I was having the same problem, but it was because I had my .env file in YAML format instead of JS.
It was
REACT_APP_API_PATH: 'https://my.api.path'
but it needed to be
REACT_APP_API_PATH = 'https://my.api.path'
For people who apply all those answers above and didn't work just restart the terminal of npm start, stop the live server and run it again and it will work because it works for me
Regarding env-cmd. As per VMois's kind post on gitHub, env-cmd has been updated ( version 9.0.1 as of writing ), environment variables will work as follows on your React project:
"scripts": {
"build:local": "env-cmd -f ./.env.production.local npm run build",
"build:production": "env-cmd -f ./.env.production npm run build"
}
In your package.json file.
1- Make sure .env file is based your react app root directory
2- for react app you need to prefix REACT_APP_ to the variable name. ex: REACT_APP_API_URL
3- kill server and npm start again after .env file modify
For this purpose there is env-cmd module. Install via npm npm i env-cmd then in your package.json file in scripts section:
"scripts": {
"start": "env-cmd .env.development react-scripts start",
"build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
}
In your project root you have to create two files with the same env variables but with different values:
.env.development
.env.production
Then exclude them from public. For this in your .gitignore file add two lines:
.env.development
.env.production
So this is a proper way to use different env variables for dev and prod.
While working with .env file, be it frontend or backend.
Whenever you modify the .env file, you must restart the respective server for the changes to take effect in the application.
Hot reloading doesn't read changes from .env file.
If the .env file works but .env.development or .env.production don't, then create an empty .env file alongside those two. I don't know why but this works for me.
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables
that doc creates confusion.
So you actually need to put prefix REACT_APP_ within the .env to make it work.
And make sure that you restart the test/dev/prod server because the .env content change was loaded on the build stage.
And remember not to have semi-colon after the API key in the env-file.
REACT_APP_API_KEY = 'ae87cec695cc4heheh639d06c9274a';
should be
REACT_APP_API_KEY = 'ae87cec695cc44heheh1639d06c9274a'
that was my error
when you get undefined from the environment file then just stop the terminal and restarts with npm start command.
For any VS Code users, be aware that the .env.local env file is auto-sourced, but also auto-ignored from search results when you do a project wide search for MY_ENV_VAR(probably due to it being git ignored by default). This means that if you have MY_ENV_VAR= in your .env.local like me and forgot about it, it'll break things and you'll spend 15 mins being very confused.
Was struggling for a good hour before I noticed my kind IDE added an import:
import * as process from "process";
just remove it and you're fine, if that's your case as well.
After you add .env file, you need to
restart your application
kill the server
run npm start again
And it should work
I had same issue that I wasn't able to access .env variable in App.js.
and I had solved the problem use create correct .env file.
in my case I was copy file from different OS and use in ubuntu system
so just I did "sudo touch .env" and added my variables and restart app again then it's working for me.
I forget to add process.env.
It looks like this
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
first step:
in your .env.local file add REACT_APP_your_API_key in this way
second step:
Add your config file ${process.env.REACT_APP_Your_API_key}
the third step:
must restart your React App and then Test whether it works.
mainly, I forget the last step
If none of the solutions above worked for you, give these potential solutions a shot:
Make sure all the import statements within the file that is requiring defined environmental variables are being imported from the local project and not some other project(VSCode wrongly autocompleted some of my import statements in this manner)
Try exiting your current Terminal instance and running the app in a new instance
I made the silly mistake of naming my file secret.env because that's how I always did it in Node.js.
After changing the name to .env, restarting the terminal, and running npm start again, everything worked like a charm
I didn't get any value back as well. For some reason, I thought the environment file should be dev.env, qa.env etc. Actually, it's just ".env". That's that. In case some else makes this mistake.
create-react does not supports hot reload feature .env files since they are not Javascript. So, when you change the env files make sure to manually start your server to see the effect of new changes.
In my case, a manual restart of the server worked fine :)
What worked for me was to install env-cmd and after that in my package.JSON add the following line of code
"scripts": {
"start": "env-cmd -f .env.development react-scripts start ",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
As of latest react-scripts (3.2.0) it's a simple as putting say
PORT=4000
BROWSER=none
in your .env or .env.development file (..etc) which is supposed to be in the root folder.
It will NOT work with then REACT_APP prefix (the docs are outdated I guess) and it does NOT require any extra npm packages (react-scripts already includes dotenv 6.2.0)

React env variables with .env

I'm trying to follow docs on adding env variables from react-create-app without success:
https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables
inside root of the document I have a ".env" file (default .env properties)
.env file contains only one variable 'REACT_APP_API_HOST=http://localhost:8080'
trying to access process.env inside my app (created with create react app) gives me undefined
This is app.js where I'm trying to access process.env without success.
I can't access process.env inside the code. Is there any working example on how to do it?
You can use .env file on root.
start: react-scripts start - uses .env.development
build_staging: "set REACT_APP_ENV=staging & react-scripts build" - uses .env.staging
build: "react-scripts build" - uses .env.production
In your package.json you will eventually have to add NODE_ENV=development at your start script. E.g. NODE_ENV=development && node scripts/start.js for the ejected create-react-app and NODE_ENV=development react-scripts start for the unejected one.
Edit: Apparently NODE_ENV=development is not required since it is already hardcoded when you run the start or build script. Per the docs your custom environment variables should have the following format REACT_APP* as you have already done.
A snippet would be helpful.

Resources