Where Should Secret Keys Should be Stored for a Node.js App ?
Last Updated :
25 Jun, 2024
In the development of Node.js applications, managing sensitive information like API keys, database credentials, and other secret keys is essential. Mishandling these secrets can lead to severe security vulnerabilities, including unauthorized access and data breaches. This guide explores best practices for storing and managing secret keys in a Node.js application.
Why Is Secure Storage Important?
Secret keys are critical to the security of your application. They are often used for authentication, encryption, and secure communication. Exposing these keys can result in:
- Unauthorized access to services and data
- Data breaches and loss of sensitive information
- Exploitation of application vulnerabilities
- Legal and compliance issues
Environment variables
An environment variables have the ability to configure a value in the code from outside your application. An environment variable is dynamic name/value pair, and one can create any number of environment variables. Environment variables are present outside the application and reside in the Operating System or container of the application where the application is deployed. Most of the applications are deployed in a development environment first before being actually deployed to the production environment. Hence, we have to make sure that each environment has been configured correctly. Environment variables have the ability to provide different configuration options for different environments.
Some common examples of Environment variables are:Â
- Database connection information
- API endpoints
- Third Party API Keys and secrets
- Email ID and password
- HTTP ports/address
Setting Environment Variable
The syntax for setting an environment variable is as follows, where ENV_VARIABLE_NAME is the name of our environment variable and VALUE is the value for that particular variable.
ENV_VARIABLE_NAME = VALUE
Node.js provides process object which is global object that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require(). The process object has a property .env which property returns an object containing the user environment.
Reading Environment Variables
To read the environment variable from .env file, we require some parser to make it work. The parser reads the variables one by one and parses them to the environment. There is an npm package called dotenv is a zero-dependency module that loads environment variables from a .env file into process.env object.
To install this package, type the following command in the terminal:
npm install dotenv
The updated dependencies in package.json file will look like:
"dependencies": {
"dotenv": "^16.4.5"
}
Require dotenv package in the app using the following code
require('dotenv').config();
Now, we can access any environment variable using process.env.[ENV_VARIABLE_NAME].Â
Example:
Let’s consider we are developing an E-commerce Node.js application where we have following environment variables like server PORT number, database connection URL & password, stripe API key, email ID and password, session secret key, etc.Â
Step 1: Create a file named ‘.env’ in the root folder of the project which will store all our environment variables. For example, our file looks like the following:
TEST.env
PORT=8080
DATABASE_URL=mongodb://localhost:27017/GFG
DATABASE_PASSWORD=<your password>
STRIPE_API_KEY=<your stripe api key>
[email protected]
EMAIL_PASSWORD=<your email password>
Step 2: Access acess and display using console.log
Example: Implementation to show accessing our defined environment variable.
JavaScript
// index.js
require('dotenv').config({ path: './TEST.env' })
console.log("PORT:", process.env.PORT);
console.log("DATABASE_URL:", process.env.DATABASE_URL);
console.log("DATABASE_PASSWORD:", process.env.DATABASE_PASSWORD);
console.log("EMAIL_ID:", process.env.EMAIL_ID);
console.log("STRIPE_API_KEY:", process.env.STRIPE_API_KEY);
console.log("EMAIL_PASSWORD:", process.env.EMAIL_PASSWORD);
Step 3: Run the index.js file using the following command:
node index.js
Output:

NOTE: Always add .env file to .gitignore to avoiding it from committing to version control systems. If you have ever commit .env file by mistake, then generate new API keys and change passwords as soon as possible to avoid any disastrous effects, and remove it from being tracked by version control system.
Similar Reads
How to Build a Simple Web Server with Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 min read
What are the Key Features of Node.js ?
Node.js has gained immense popularity among developers for its ability to handle server-side operations efficiently and effectively. Built on Chrome's V8 JavaScript engine, Node.js is designed to build scalable and high-performance applications. Here, we explore the key features that make Node.js a
5 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.j
4 min read
Folder structure for a Node JS project
Organizing a Node JS project with well planned folder structure is crucial for readability, scalability, and maintainability. A clear structure helps in managing code, configurations, modules, and other assets effectively. In this article, we are going to learn the folder structure of the Node JS pr
5 min read
How to Reset / Change Password in Node.js with Passport.js ?
Resetting or changing passwords securely in Node.js applications using Passport.js typically involves a combination of strategies, including token generation, email communication, and password hashing. Let's go through the steps required to implement password reset functionality using these tools. S
5 min read
Build a Node.js-powered Chatroom Web App
In this article, we are going to create a chatroom web app using Node.js. A Chatroom Web App is basically used to create a chatroom that is similar to a group chat, where users can come and join the group/ chatroom, send messages to the chatroom, and see other users' messages. We are going to set up
5 min read
Why to Use Node.js For Backend Development?
JavaScript is the universal language for building web applications. It is used in frontend (client-side) and backend (server-side) development as well. But the truth that the beauty of the front-end relies on the back-end can't be denied. This is when NodeJS comes into the picture. NodeJS is the bes
7 min read
How to Manage Users in Socket.io in Node.js ?
Socket.IO is a library that enables real-time, bidirectional, and event-based communication between the browser and the server. Managing users in Socket.io and Node.js typically involves handling user connections, disconnections, and broadcasting messages to specific users or groups of users Prerequ
10 min read
Node.js Securing Apps with Helmet.js
Helmet.js is a Node.js module that helps in securing HTTP headers. It is implemented in express applications. Therefore, we can say that helmet.js helps in securing express applications. It sets up various HTTP headers to prevent attacks like Cross-Site-Scripting(XSS), clickjacking, etc. Why securit
4 min read
Why Express âappâ and âserverâ files kept separately ?
In Express.js applications, separating the app.js and server.js files is a best practice that makes the project more organized, scalable, and easier to maintain. Let's dive into why this structure is commonly used and how it benefits developers working on Express projects. The Importance of Separati
4 min read