Enviroment variables react - javascript

I have a react component which in development will redirect to a localhost url but in production to a different url. In my backend I have the same situation and there i solved it with a package called dotenv. I was wondering how someone would do this in a react front-end.
export default withRouter(function Login(props) {
useEffect(() => {
if(localStorage.getItem('jwt')){
props.history.push('/dashboard');
}
})
const handleLogin = () => {
window.location.href = "http://localhost:8000/auth/google";
}
return (
<LoginView handleLogin={handleLogin}/>
)
})

You can use dotenv to add environment variables to react as well. During app deployment(in the build process) the environment variables must be replaced with the corresponding URLs (as this is the most frequently encountered use case in front-end applications). This can be done while configuring the build process.
Here is an example using Webpack https://medium.com/#trekinbami/using-environment-variables-in-react-6b0a99d83cf5
The whole idea here is to create a file (called just .env) filled with
your environment variables. To prevent people from finding out your
local database password is the same one you use for every single one
of your accounts on the internet , I urge you to add the .env file to
your .gitignore. Your front-end code will refer to the same
environment variable (process.env.API_URL) on both environments
(development/production), but because you defined different values in
your .env files, the compiled values will be different.
I would suggest having a separate .env file for the react app as it should not be accidentally served with the website.
Create React App has a module(built around the node dotenv module) you can use for adding custom environment variables
https://create-react-app.dev/docs/adding-custom-environment-variables/
The environment variables are embedded during the build time. Since
Create React App produces a static HTML/CSS/JS bundle, it can’t
possibly read them at runtime. To read them at runtime, you would need
to load HTML into memory on the server and replace placeholders in
runtime, as described here. Alternatively you can rebuild the app on
the server anytime you change them.

Its depend on how you are using react.
If you are using react-script, you can go will above solution(https://create-react-app.dev/docs/adding-custom-environment-variables/).
But if you are using webpack, try to use DotenvPlugin in place of dotenv module (https://webpack.js.org/plugins/environment-plugin/).
In my opinion, pls don't follow method 1 use in medium link, as env should not be push on git but package.json need to be done.

Related

How can I create environment variables and use them in a react library, without using webpack?

I have tried dotenv and cros-env. And also with mentioning it in this link
https://create-react-app.dev/docs/adding-custom-environment-variables/
However, it doesn't work for me
My .env file
MY_VAR=value
I have this in the file where I want to call it
console.log(process.env)
const { MY_VAR } = process.env
console.log(MY_VAR)
and i get this
As noted here, environment variables for your frontend must begin with REACT_APP. So try REACT_APP_MY_VAR and restart your React server afterwards.

How can I set environment variables on netlify?

I have a netlify react app. which is connected to my github. I'm using emailjs for receiving the messages from whoever reaches to my app.
emailjs deals with three ids 'SERVICE_ID', 'TEMPLATE_ID' and 'USER_ID'. But I don't wanna use them openly in my component js file.
Driver Function
function sendEmail(e) {
e.preventDefault(); //This is important, i'm not sure why, but the email won't send without it
emailjs.sendForm(SERVICE_ID, TEMPLATE_ID, e.target, USER_ID)
.then((result) => {
window.location.reload() //This is if you still want the page to reload (since e.preventDefault() cancelled that behavior)
}, (error) => {
console.log(error.text);
});
}
I think you're referring to environment variables, in order to test that out locally it will vary per the stack you use for creating the app, if you use react create app you can create a .env file in the root of your project and populate the values
REACT_APP_SERVICE_ID ="your_value"
REACT_APP_TEMPLATE_ID ="your_value"
REACT_APP_USER_ID ="your_value"
Don't forget to exclude this file from git, to avoid pushing secrets in your repo. to do that add this to your .gitignore
.env
After that you can call the variables in your code using the process.env like this:
process.env.REACT_APP_SERVICE_ID
Now modify the code:
function sendEmail(e) {
// Your code
emailjs.sendForm(process.env.REACT_APP_SERVICE_ID, process.env.REACT_APP_TEMPLATE_ID, e.target, process.env.REACT_APP_USER_ID)
// your promise
}
To make that work in netlify you would have to add the variable in your netlify project, follow this section to do that: https://docs.netlify.com/configure-builds/environment-variables/#declare-variables
As you noted I added the prefix REACT_APP_, this is because react create app does this:
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.
If you are using gatsby or nextjs the env variables naming convention might change so please be aware of that.
You can set env variables on netlify. Please have a check the below images.
Check Adding env variables to react app
You can create a .env in your root dir and add your keys, api end points,... inside of it.

Dotenv Webpack - When I change the system environment variables on runtime, the changes is not affected on the app

I build a web app using react, webpack, docker and AWS.
I create a feature which depends on environment variable. So if the environment variable value is true, the feature will be showing on the frontend.
The problem is, when I changed the environment variable on the server (Webpack already done building the app, the app is already deployed and running), my feature is not showing. I guess due to the app cannot read the value changes on system environment variable.
How can I achieve this ? is it possible to do it ?
=====
I use dotenv webpack for managing my environment variables. I already set the systemvars to true to detect all environment variables from the system or .env file.
=====
So why am I doing this, because I dont want to make a Pull Request to push a new value for environment variables. I just want to reserve the environment variables name, and change the value directly from the server if the feature is ready to deployed. And if there is an error, I just need to change the environment variable to something and the feature is down.
You simply cant change environment variable. Evn variables loaded on compile/webpack load time. So once app start u cant change, process.env.
Solution as #jonrsharpe explains. You need to create, some sort of database. It could be memory or file or database. You read data from that. Expose a API, to update the data base.
Express sample:
global.enableFeature = false
app.post("/updateFeatureToggle", (req, res) => {
const enableFeature = req.body.enableFeature
global.enableFeature = enableFeature
res.send({success: "OK"})
})
In another file, read from global.enableFeature. This is in memory-based.

How to edit .env file after build completed reactjs

i had build react app web page
with custom environment variables
the problem is when i build the script
and change the .env variables no thing change in the website !
.env file :
REACT_APP_SITENAME=TheSiteName App
After building a react app all code is static and can't be changed. I think the only solution to send some dynamic data to your react app is to either create a special file per system you running your app on and load this directly inside the index.html or create the content of this file on the fly.
So when you're using create-react-app in public/index.html add something like this:
<head>
...
<script src="https://www.example.com/envconfig.js" type="text/javascript">
</script>
...
</head>
This file should contain the environmental config, e.g.:
window.globalConfig = {
siteName: "The Sitename App"
}
The file can also be created on the fly by PHP, Java or any other backend service. Just make sure to answer as valid Javascript.
And in your React app at index.js, App.js or anywhere you can access this variable as it is global:
const appConfig = window.globalConfig || { siteName: process.env.REACT_APP_SITENAME}
With this you've got an fallback to the static env config if globalConfig is not available, likely in development.
Now you can use appConfig in any way and provide it via redux, context or property to your components.
Last thing to mention, you have to make sure that the config-file is loaded before executing all the React code. So the file should be loaded before all the created React files.
Quote from the docs:
The environment variables are embedded during the build time.
It isn't possible to apply environment changes as runtime.
Reference
Here is an example of how to use the environment at runtime:
CodeSandbox
here is an idea:
add a json file (e.a. config.json) with your configuration to the "public" folder. That file will be in the root of the build:
{
"name": "value" }
in your React code, create a static class with the variable you want to configure:
class Config {
static name= "[default value overwritten by the config]"; }
somewhere high in the startup of your React application, read the json and set the static variable:
fetch("config.json") .then((r) => r.json()) .then((data) =>{
Config.name=data.name; })
now you can use that config anywhere you need it :
Config.name
Note that any configuration you make will be vulnerable for public eyes, since the file can be opened directly with a URL. Also note that when deleting that json file, everything will still work with the default value. You could implement some check that the file must exist.

react-create-app ENVIRONMENT variable configuration

i am creating react application using create-react-app,i am using node js as a backend development.
i can run it successfully in the local environment,but while having same application in the production build application doesn't set the "apiURL"
my backend url is=http://localhost:5001/
API_URL = process.env.REACT_APP_API_URL
actually i need to get my API_URL = http://localhost:5001
but i am getting API_URL is undefined in the production deploy
and on request of some backend api i am getting
http://localhost:3000/undefined/api/someapi
but actually i need to get the
http://localhost:5001/undefined/api/someapi
can any one help how can configure my environment variable dynamically depends on the host environment
sorry for my bad english
thanks in advance
You need to set different values of your variables depending on your environment. There're multiple possibilities, you can for example do it on script level in your package.json:
"scripts": {
"deploy:staging": "REACT_APP_API_URL=<paste-your-api-for-staging> ...",
"deploy:production": "REACT_APP_API_URL=<paste-your-api-for-production> ...",
}
Or you can use my personal favorite -> https://github.com/motdotla/dotenv for managing your env variables. It's based on different .env files for eg. .env.local or .env.production where you can set your values.

Categories