How to edit .env file after build completed reactjs - javascript

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.

Related

Unable to access process variable in Vue3JS Vite project

I am creating a vue3 application (created with Vite) that interacts with a smart contract written in Solidity and stored on Ropsten. Therefore I am using web3js to interact with my smart contracts and also web3.storage in order to store some images on IPFS. I have a .env file at the root of my project storing my API key for web3.storage :
VUE_APP_API_TOKEN=VALUE
VITE_API_TOKEN=VALUE
The problem is that apparently web3.storage expects the API token to be stored in process.env and I am unable to access the global process variable from my application. I am always getting an error Uncaught ReferenceError: process is not defined.
I think, this is linked to my usage of Vite instead of pure Vue3.
I tried to export process env in the vite.config.ts file with that code but it didn't work:
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };
console.log(process.env.VITE_API_TOKEN) //Works fine: VALUE is logged
console.log(process.env.VUE_APP_API_TOKEN) //Works fine: VALUE is logged
return defineConfig({
plugins: [vue()]
});
}
How could I access the process variable from my vue files in order to get the values of my environment variable and make web3.storage work?
.env
VITE_WEB3_STORAGE_TOKEN="your_token"
SomeComponent.vue: (or any other file of your app, really):
console.log(import.meta.env.VITE_WEB3_STORAGE_TOKEN) // "your_token"
Note: as specified in vite documentation, only variables prefixed with VITE_ will be exposed:
To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.
If you're running the build script in CI you will need to make sure that you're creating / populating the relevant .env file before you run the build script.

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.

Use configuration file to initialize a node_modules library

I made a react component library that I would like to use in multiple projects.
I need to use different variables depending on the environments, for this reason I was thinking of using an initialization file (eg: my-library.init.js) in the host app that exports a config variable, but I don't know how to make the library read this variable from host app.
the file should look like this:
export const config = {
envs: {
S3_URL: 'https://my.dev.url.org'
ENV: 'dev'
}
}
Any help will be appreciated
Tahnk you

Enviroment variables react

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.

configurable vue frontend application

Im working on a Vue frontend that consumes a backend API that are both being deployed to the same kubernetes cluster. I would like to make the vue frontend application configurable so I can assign the address to the backend service on container startup instead of during build time.
I've been trying to do this by following Hendriks answer to this thread:
Pass environment variable into a Vue App at runtime
Due to my lack of Node and Javascript experience, I do not understand the following:
Where in the filestructure the files should be placed?
Why the config.js describes a function, and not just as export default { configObj: var } an object with the variables?
How I can access the variable in config.js through /config.js in the rest of my app? I can see the file in my browser at /config.js, but imports does not work.
I've currently placed the files like so:
/app
/public
index.html << I put the script tag in the head of this file.
...
/src
/config
config.js
main.js << setting axios.defaults.baseURL here. import config from '#/config/config.js' results in the str 'config.js'.
...
vue.config.js
Even though I know my backend service IPs/addresses are not supposed to change in production, setting these values before build seems like a very static and manual way to do it. During development running the app and backends locally on minikube, waiting for long builds quickly becomes very time consuming.
Very greatful for any insight in how I can achieve this, or any insight into why I can't seem to get Hendriks proposal to work.
It's important to note that what you are trying to do doesn't have anything to do with node. The execution environment of your Vue app is going to be the browser and not node (even if you are serving it with node). This is also why you can't do export default of your config, as some browsers won't understand that.
But here is a method you can use in order to get the config to your app using k8s.
Create a k8s config map, which will contain your config.js, something like:
apiVersion: v1
kind: ConfigMap
metadata:
name: vue-config
data:
config.js: |
function config () {
return { serverAddress: "https://example.com/api" };
}
Then in your pod/deployment embed the file:
apiVersion: v1
kind: Pod
spec:
containers:
- name: your-vue-app
image: your-vue-app:1.0.0
volumeMounts:
- name: config-volume
mountPath: /app/public/config.js
volumes:
- name: config-volume
configMap:
name: vue-config
Note that you are putting the config in the public directory. After that you can add the script tag in the index, which loads the config.js. Having the config as a function is useful, because you ensure some level of immutability, also I think it looks a bit better that a global config var.
When you want to use the configuration, you just call the config function anywhere in your configuration:
const conf = config();

Categories