How to load secrets in Node.js
Our application will need to connect to MongoDB, so we need to store the connection string in a safe place. You should never store secrets in your code; a very common practice is to store them in environment variables. In this section, we will explain how to load secrets from environment variables in Node.js.
Environment variables
Environment variables are variables that are set in the environment in which the process runs. They are usually set in the operating system, but we can also set them in the terminal. We can access the environment variables in Node.js using the process.env
object:
console.log(process.env.MY_SECRET)
You can set an environment variable in the terminal with the following command:
export MY_SECRET=secret
Then, you can run your application with the following command:
node index.js
Alternatively, you can set the environment variable in the same command:
MY_SECRET=secret node index.js
Important note
If you...