Understanding .env file and environment variables in React JS - javascript

I'm relatively new to web development world and now I'm trying to understand the usage of .env file in React JS. So, I have read multiple articles and watch some explanation videos. However, most of them were focusing on how to use it rather what it actually is. Do I understand correctly that the main benefits of using environment variables are:
1)They make it easier to maintain applications since they all stored in one file .env
2)They are not visible to users and are not shown and uploaded to Git repository
Is it correct and is there anything else I need to consider?

They are useful to store site-wide values and settings that don't belong in state or as declarations (deep) in the source.
Important to know is that, for react to use them, they have to start with REACT_APP_. This is due to the environment is a nodejs one, and nodejs will claim all variables unless they start with REACT_APP_
Environment variables starting with REACT_APP_ are embedded in the app code during build time.
Do not store any secrets (such as private keys) as REACT_APP_ variables in there! That will expose them in the JS build.
In your react app you can access the variables like so:
let value = {process.env.REACT_APP_MYVALUE}
In HTML you can use the variables as such:
<title>%REACT_APP_SITE_NAME%</title>
A good quick read on usage with create-react-app: https://create-react-app.dev/docs/adding-custom-environment-variables

Usage
Environment (.env) variables are used to store sensitive information, or as the name says, environment-focused information (live, development, debugging, etc...)
.env file is also kept inside .gitignore, so it does not get pushed to any repositories.
Keeping track of variables
.env.example is a file which is not kept in .gitignore, but it is needed for other developers to know how and what to put in their .env. It looks something like this:
.env.example:
REACT_APP_STRIPE_KEY=
MY_SECRET_KEY=
THIS=
FOO=
BAR=
Basically an empty example of what would be .env. This then gets copied and filled with real values in a .env file, which is only available for that developer on that computer, and is read locally by the scripts which then know in what mode to start the app, connected to what database, with what password etc.

Create a file in the root folder.Its .env file
REACT_APP_(VARIABLE_NAME)=KEY_HERE
Usage:
when you added a variable in .env file. Restart your app.
console.log( process.env.REACT_APP_(VARIABLE_NAME) )
And your .gitignore file, add the bellow code
.env

Related

How to read/pass vercel system enviroment variables to code in Sanity?

I want to pass the VERCEL_GIT_COMMIT_REF variable to my javascript bundle. I've deployed Sanity in Vercel and it only passes variables with the prefix SANITY_STUDIO_.
So, I've created an environment variable named SANITY_STUDIO_VERCEL_GIT_COMMIT_REF and want to pass VERCEL_GIT_COMMIT_REF into it.
I tried a few ways but it doesn't seem to work!
Here is what I want to achieve:
You can map environment variables by creating a .env.production file.
SANITY_STUDIO_VERCEL_GIT_COMMIT_REF=${VERCEL_GIT_COMMIT}
https://www.sanity.io/docs/studio-environment-variables#f5e9e3158896

Hiding API keys in JS setup

I'm creating a simple UI with an HTML+CSS+JS setup that uses a third-party API requiring a key and I'd like to keep the key in a file that I can gitignore and access from my Javascript file. I'm not going to be deploying this project, I just want to be able to push it to GitHub without temporarily deleting the variable before every commit.
All responses I've found are related to setups with Node.js, React/Webpack, or other server setups, but I don't have a server or transpiler and don't want to add a bunch of cruft and configurations just for this. Is there a way to do that? I tried storing it in a separate JS file and import/export, but either I couldn't get the syntax right or what I was trying needed a transpiler. Every attempt variation resulted in a syntax error or undefined variable.
Key information:
This is project run entirely locally--as in, just opening index.html in my browser--so I don't think I need to worry about the key being exposed in the client.
My setup pretty much just includes index.html, main.js, and style.css.
I want to push the project to GitHub, so I want to store the api key as a variable in a file separate from main.js that I can add to .gitignore but access in main.js.
I'm keeping this as simple as possible without frameworks, etc. Unless it's super simple and lightweight, I don't want to add libraries just to get this working.
Your best bet is to pull whatever secrets you need from the environment itself, either your environment variables or a secrets store.
The specific implementation will depend on what serverless provider you're using, but for example AWS Lambda lets you configure env vars:
https://docs.aws.amazon.com/lambda/latest/dg/env_variables.html
and you can use the Key Management Service or Parameter Store depending on your preference and requirements:
https://aws.amazon.com/blogs/mt/the-right-way-to-store-secrets-using-parameter-store/
Leaving the above in place in case folks find this via looking at the Serverless tag. Updates below based on the updated question.
So, if I understand the updated question correctly, you want to check in all your code to git except the API key, serve the files only on your local file system and have that local copy be able to access the API key.
The simplest way to do this would be to just have another .js file that defines the variable(s) in question like so:
// config.js
var config = { // this should be const instead if you're using ES6 standards
apiKey : '123456789XYZ'
}
Then, in index.html have another script tag that calls that before any scripts that need the config, e.g.:
<script src='./config.js'></script>
<script src='./main.js'></script>
</body>
In main.js you will then be able to reference the variable config for use, and similarly you can .gitignore 'config.js'.
If you use MVC, try to write in php variabel. Than open in script javasript with echo ...

How to use .env file variable in .js file other than Keystone.js?

We are using keystone frame work in one of our project and i am trying to use .env file variable to one of my .js file to connect with http site.I have used dotenv and called process.env.xxyz where xxyz is the variable we are using.Please let me know if there is any other method to call variable from .env file.
Reading process.env is the standard way to retrieve environment variables. See the docs.
The dotenv package you mentioned takes what is in your .env file and puts it in process.env. However, no validation is performed, so it is easy to make mistakes.
Instead, try out my envy module which prevents all of the common mistakes you might be making. It checks for missing variables, amongst other things.
If .env files are still giving you trouble:
Make sure you are using the correct variable names.
Make sure there are no typos.
Make sure you are using the proper syntax.
Consider using command line arguments instead. I recommend meow for this. Also see an example of using envy and meow together.
Regarding syntax: depending on which loader you are using (e.g. dotenv vs envy), the syntax in the .env file could have a big impact on how it is parsed. For example, in Bash and other shells (which the files are based on), each and every one of the following examples behaves entirely differently...
MY_VAR=foo $BAR
MY_VAR='foo $BAR'
MY_VAR="foo $BAR"
Also, environment variable names are case sensitive and by convention are all uppercase. This can lead to mistakes in languages where that is uncommon. In the Node.js program reading process.env, sometimes you might forget that the naming conventions for environment variables are different than the rest of the program.
const myVar = process.env.myVar; // wrong
const myVar = process.env.MY_VAR; // correct
Casing is not an issue if you use envy, as it fixes this by normalizing variable names to camelcase before returning them.
const { myVar } = envy(); // correct, no matter how it is in `.env`
Regardless of which loader you use, you will of course need to call its load function before the .env file will be read. This is pretty much impossible to forget with envy() because you use only its direct return value. But if you are using dotenv, you can easily access process.env at the wrong time because it is already available and populated (but not with all the desired properties) before calling dotenv.config().
Another trick that will help with debugging and save time and effort is to make a dedicated module for configuration. Thanks to the require cache, we avoid doing the work multiple times and also avoid relying upon the loader being idempotent.
Put this in a file called env.js.
const envy = require('envy');
module.exports = envy();
Then import it elsewhere.
const env = require('./env');
Now you have something very simple to debug and it should work the same no matter where you import it.
Just add xxyz=HTTPSiteAddress to your .env file. Then you can call the variable anywhere by using process.env.xxyz.
For example:
var request = require("request");
request(process.env.xxyz, function(error, response, body) {
console.log(body);
});
This will work as long as your keystone.js file contains at the top:
require('dotenv').config();

How to select file to copy based on Docker environment variable?

My problem is that I have some URLs hard coded in a Javascript file. They are specific to the environment where I deploy my docker image. Here is a example of the different urls I need to have.
For the live ENV:
export const BLUE_SERVICE = 'https://myliveserver/api/blueservice';
export const RED_SERVICE = 'https://myliveserver/api/redservice';
For the release ENV:
export const BLUE_SERVICE = 'https://myreleaseserver/api/blueservice';
export const RED_SERVICE = 'https://myreleaseserver/api/redservice';
My idea was to have two versions of the file. I would then copy one or the other based on an ENV VARIABLE in my dockerfile. By the way I already have a ENV VARIABLE called STAGE
Perhaps there is an other (better) solution to do this. Any idea?
You could use build-time variables instead:
docker run –-build-arg BLUE_SERVICE='...' –-build-arg RED_SERVICE='...'
This flag allows you to pass the build-time variables that are accessed like regular environment variables in the RUN instruction of the Dockerfile.
Also, these values don’t persist in the intermediate or final images like ENV values do.
You could generate two images which would, in their Dockerfile, generate the right javascript file using the right value for BLUE and RED SERVICE.

How to use javascript constant in javascript file from another javascript file

I have created one javascript file in which I have declared different string constants.
now in another javascript file I want to use those String constants from already created javascript file.
Is there any way to do this.
Thanks in advance.
If you declare your constants in file1 as global variables:
var someConstant = 42;
Then you can just use that variable in your other JS files. Just make sure file1 is loaded before you try to use them.
However, polluting the global scope like this come with it's risks, as those variables are easily changed.
Multiple ways.
Concatenate
Use a task runner like grunt to define a task that concatenates your files into a single one. This will not only allow convenient definition of constants but also improve performance.
There are other tools to do this, too. See Prepros for windows and codekit for Macs.
Modularize
If you are on client side, use a tool like require.js or browserify to define commonJS / AMD modules and require them as you need.
If you are on server side using node, this works out of the box for commonJS.
Load scripts in correct order, expose them through global objects.
You could load your constant defining script first and do something like this:
var constants = {
MY_CONST: 'Foo'
}
Your main, whi script could access this variable. If you omit the var keyword, the variable becomes globally available. Note however that this should be avoided.
You could even add a property to the global object (window on the client side).
Personally I like to use commonJS modules when working on projects that allow me to do so. Rob Ashton has an opinion on this that I would like to share.
When I can't use those modules in a convenient way, which would be the case when working with (custom) web-components because of their isolated scopes, I like to add a single script which creates
an Object like App. I use this object to expose modules, services & constants which can then be required by any component in a neat way:
App.myService.doSomething()
Create a file which contains all the constants and variables
Constants.js
const EMAIL = "xyz#gmail.com"
const PHONE = "9911223344"
var NAME = "Default name"
Access the Constants.js file in your HTML file
xyz.html
<script src="Constants.js"></script>
Now you can access the Constants in any of file inside a project

Categories

Resources