React app unable to access root's env file - reactjs

Context:
- MERN stack app
- Deployed to Heroku
- React app created with create-react-app
Here is my folder structure:
folder structure
In my server app.js, I can access the .env variables by requiring it like this: require('dotenv').config({ path: '../.env' });
I am trying to access the env variables on my React app, but I cannot seem to access the variables in the root .env file, and I cannot seem to specify the path in React (can I?) for the .env like in server/app.js.
The only way I can get it to read any .env variable value is if I move the .env file to the client directory, so my workaround for now is to move .env to my client directory and update the code in my server to require it as such: require('dotenv').config({ path: '../client/.env' });
This workaround fixes it, but is there a better way/best practice to allow for the .env file be in the root folder?
Do I need to eject create-react-app and set up some custom configurations?
More info:
My local .env file contains:
REACT_APP_API_URL=http://localhost:5000
My client/package.json scripts:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},

Sorry, miss understood your question.
In create-react-app you don't have to require the dotenv module, ref: https://create-react-app.dev/docs/adding-custom-environment-variables/
Are you sure your local environmentis development?

Related

How to rename 'index.js' file in React File structure to something else?

In the React file structure under components there is index.js file that runs the main character when running the project. Is there anyway to rename this file to any name I want? I am using PM2 server manager and there is no way for me to keep track which server is which when running multiple index.js files. So the only option I got is to rename this index.js to something specific to each project.
I have tried changing the package.json file's start script as below but nothing worked out only gave errors.
"scripts": {
"start": "test.js react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Appreciate all your help!
You can't change the name of the file used by create-react-path.
You'll have to either eject to use custom webpack config by running
npm run eject
But it's a one-way operation (see documentation)
Or you can use Vite instead of create-react-app to bundle your project.
Vite is more configurable than create-react-app, you define in the index.html the name of your js file. So you can put any name you want.
Maybe even this example could help you:
https://vitejs.dev/guide/ssr.html#example-projects

Not able to fetch .env urls to my component on my react project

I am using 3 .env file like .env.prod, .env.dev and .env. But not able to fetch the url to my component.
I am using react 16.9.
Can you please help me why I am not able to fetch it?
in my .env / .env.dev files
loginUrl = = "http://localhost:8080/api/2.0/admin/auth/login"
in my package.json files
"scripts": {
"start": "cp ./.env.dev .env && react-scripts start",
"build:dev": "cp ./.env.dev .env && react-scripts build",
"build:stage": "cp ./.env.stage .env && react-scripts build",
"build:prod": "cp ./.env.prod .env && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},```
Inside my component, when I am printing it it is giving undefined.
console.log(process.env.loginUrl) is giving undefined
Using react-script
Looking at react script adding-custom-environment-variables documentation, variables are automatically loaded from .env if:
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.
Seams like the problem come from the name of your variable, try renaming in REACT_APP_LOGIN_URL
Note: this feature is available with react-scripts#0.5.0 and higher.
If using Webpack instead of react-script
You need to use webpack DefinePlugin to inject environments variables in your code.
In your webpack.config.js file :
require("dotenv").config(); // will load .env file in process.env
const webpack = require("webpack");
...
plugins: [
...
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production"),
SENTRY_DSN: JSON.stringify(process.env.SENTRY_DSN),
BUILD_DATE: JSON.stringify(new Date()),
TRAVIS_COMMIT: JSON.stringify(process.env.TRAVIS_COMMIT)
}
}),
...
]
Make sure you have strings only as if the value isn't a string, it will be stringified (including functions).
Then in your code, you can call console.log(process.env.NODE_ENV)

define .env file except default env file in react app

I need to load for each development/production server a different .env file.
localhost | .env.localhost
development | .env.development
production | .env.production
base on react documentation, by default we can use .env.development and .env.production
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
but i want to use new environment variable as localhost. how can i do that? i want to run one of my script by .env.localhost variable's file.
you can modify script part of package.json from:
"start": "react-scripts start"
for Linux and MacOS to:
"start": "PORT=3006 react-scripts start"
Windows to:
"start": "set PORT=3006 && react-scripts start"
And if you want to set new variables in environment. Then add then in .env files of shell, but start name with REACT_APP for ex
REACT_APP_MY_VAR

How to deploy React app (create-react-app) to Back4App?

I've created an React app with create-react-app and I want to deploy it to Back4App.
The problem is I want to deploy the build folder and not the public folder (which I understand is the default for Back4App / ParsePlatform).
So far, I haven't found any way to config deploy to use anything other than the public folder.
Any solution / workaround to this?
If you are using B4A CLI, one of the easiest ways to deploy a create-react-app is, firstly, changing the build script into your package.json as below snippet:
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && cp -r build/* {{PATH-TO-YOUR-B4A-APP}}/public",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
...
As you can see, you just need to move all content inside create-react-app build folder to the public folder of your cloud code. After that, move to your app path and run b4a deploy.
Also, you could add a step to clear all public folder content before move the new stuff, but be careful with this step.
Otherwise, you could access the Back4app Parse-Dashboard into the Cloud Code Functions and deploy all the build stuff in public folder using the browser interface.
This is a live demo of a create-react-app deployed in Back4App.

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)

Resources