prelude
Env files can be seen everywhere in modern front-end projects, which are some of the configuration items in the project, can be used in the project, although this is a small thing, but these. Env files in the front-end engineering is useful and meaningful.
Let’s take a look through this passage.
process.env
Front-end projects now use Node as a development aid, and Process is a global variable in Node.js that provides information about and control over the current Node.js process. Env in Process returns the object containing the user environment.
In plain English, you can get information about the current project environment through process.env.
Basic Mac environment information:
// index.js
console.log(Object.keys(process.env));
Copy the code
Setting environment Variables
1. Command line
To add some customized configurations to environment variables, you can directly set them on the command line interface:
console.log(process.env.PROT)
Copy the code
PROT=10086 node index.js
Copy the code
At this point, PROT is included in the environment variable of the project run.
If you need to customize other variables, you can continue to add parameters as keys:
PROT=10086 NDOE_DEV=development node index.js
Copy the code
Although this approach is simple, it has many drawbacks:
- Poor readability: can’t see the configuration of environment variables intuitively (hot eyes)
- Prone to typing errors: If not only the port number, but also the database information, application key, etc., type all one line (manual header)
- Unmanageable: How to remember or manage all environment variables and their values (manual dog head)
So there is a way.
Env file
create
Create an.env file directly in the project root directory, then type the environment variables and their values.
NDOE_ENV=development
PROT=10086
APP_KEY=***********
HOST_URL=**********
Copy the code
⚠️ Note: do not put. Env in code versioning as these environment variables are private data in the project and risk exposure.
read
After creating the.env file, you can write your own code to find the parse file and write it to your project, or take advantage of a third-party NPM package like Dotenv to view the REPO here.
yarn add dotenv
Copy the code
// .env
PROT=10086
Copy the code
const dotenv = require('dotenv');
dotenv.config();
console.log(process.env.PROT); / / 10086
Copy the code
Instead of passing in environment variables and their values when you execute a command script, you can see and manage the configuration of environment variables more intuitively in the.env file.
Better Organization
If environment variables were not organized, they would look something like this:
process.env.PORT
Copy the code
But once there are a lot of environment variables, are they used everywhere? Or is it better to manage all environment variables centrally?
Clearly the latter.
Refactoring and maintenance can be more difficult than centralized management, because directly referencing variables in all the places that need to be used.
So it’s a better way to create a module that collects environment variables so that you can easily look at them once and map them to readable names.
Manual sorting
Create a file called config.js, then write variables, map them as readable properties, and export them.
Such as:
const dotenv = require('dotenv'); Dotenv. Config ();module.exports = {hostUrl: process.env.host_URL, secretKey: process.env.api_key, port: process.env.port};Copy the code
It can then be used like this:
Const {port} = require ('./ config'); Console. log (' port: ${port} '); / / 10086Copy the code
What’s the good of that?
- Project file organization is more intuitive and reasonable
- Clearly understand the mapping of environment variables
- Rename variables to more readable properties
- You can add configuration properties that are not environment variables
But if you want to add a new environment variable, you must add it to the Config module.
That’s the manual way. Is there an automatic way to collect?
B: of course!
Automatic sorting
The aforementioned third-party NPM package Dotenv does just that.
// config.js
const dotenv = require('dotenv');
const result = dotenv.config();
if (result.error) {
throw result.error;
}
const { parsed: envs } = result;
console.log(envs);
module.exports = envs;
Copy the code
It can then be referenced in other modules like this:
const { HOST_URL, API_KEY, PROT } = require('./config');
Copy the code
So it’s up to you which way you want to go now, and either way, you need to consider whether to make DotenV a dependency on your project to run.
It is recommended to collate environment variables manually to remove dotenv dependencies, but only if you do one more thing: preload environment variables.
Reduce reliance on
There are many dependencies in a normal project, but you should think about how to minimize them. The NPM package Dotenv is handy, but it doesn’t need to be a dependency at project runtime. Dotenv provides an option in which you can preload variables outside of code.
But how do you remove the dotnev runtime dependencies and then retain its features?
1. When installing Dotenv, install it as a dev dependency and remove all dotenv code.
2. Then use the -require(-r) option to preload dotenv.
// config.js
module.exports = {
port: process.env.PORT
};
Copy the code
// index.js
const {port} = require('./config');
console.log(The port number is:${port}`);
Copy the code
node -r dotenv/config index.js
Copy the code
The production environment
Development can read environment variables through dotenv preloading, but what about production?
In building the application of 12 elements in the guide also pointed out that the application needs and configuration, the best way is to preserve the environment variable, think that these basic configuration is the port number, service account vouchers, database links, such as private information, if the project’s configuration is stored in the code, or joined the code version management, The chances of your project exposing this intimate information are high.
If you still don’t know what the 12 elements are, you can check out the 12 Elements to Build Your Application.
Env is a private file and should not be subject to version control, according to the config element.
If running on the cloud server, you can use the functions provided by the cloud service provider to set. Or use Azure, a third-party service platform, to manage environment variables. You can start the Node project through its CLI and get the environment variable information from the cloud service platform.
If running in Docker, you can use the Docker functionality to load environment variables.
Details of how environment variables are configured in production will be covered in a future article.
How to share
The. Env file saves the configuration information of the project, which is private and cannot be exposed. How can you share the configuration information with others in the project team?
.env.example
You can create an.env.example file in the project root directory and write the key values for all environment variables. Then you can write false values or key descriptions. In the readme.md file of the project, instructions are given on how to obtain the value of setting environment variables.
Such as:
// .env.example
APP_ENV=development
NODE_ENV=development
HOST=app.test.com
PORT=10086
GOOGLE_MAP_API_KEY=the-google-map-api-key
Copy the code
Environment variable configuration information can also be stored in third-party storage management systems, such as Vault, which provides secure storage (key/value) and control over tokens, passwords, certificates, AND API keys.
Persistent configuration
Configure the service using either a custom service or Azure’s open source persistence service, and then use the SDK on the server to fetch environment variables.
However, general cloud service providers will package this service, because only the server and persistent configuration service are provided by the same supplier, the supplier can associate the persistent configuration with the server permissions, so that the third-party server cannot access the configuration even if it gets the Token.
Encryption services
If the security level of the project is high, then the encryption service can be used.
- Register with the encryption platform and get the key
- Set the environment variable in the encryption platform, which encrypts the content
- The Node SDK was used to obtain the ciphertext output from the encryption platform
- Decryption into plaintext using SDK and key
The last
Environment variables should exist outside of the project code and only be available at run time of the project, thus separating the configuration of the project from its code so that the project can be easily deployed in different environments.
For modern front-end applications developed with Node.js as an aid, environment variables can be used with the process.env global variable or set when running the Node command, or dotenv can be used.
Finally, it is important to note that.env files should never exist in source code repositories.
Reference article:
- Medium.com/the-node-js…
- Juejin. Cn/post / 684490…