Home >Web Front-end >JS Tutorial >Managing Environment Variables in Node.js with dotenv
When developing applications in Node.js, managing sensitive configuration values securely is crucial. These values—such as API keys, database credentials, and server ports—are often stored in environment variables. The dotenv package allows us to load these variables from a .env file, keeping them out of our source code while still being accessible within our application.
In this article, we'll explore how to efficiently manage environment variables using dotenv and create a utility function to ensure that required variables are always available.
Using environment variables provides several benefits:
Before we can use dotenv, we need to install it in our project:
npm install dotenv
In the root of your project, create a .env file and define your environment variables:
PORT=5000 FRONTEND_URL=http://localhost:3000 NODE_ENV=development DB_CONNECT=mongodb://localhost:27017/mydatabase ACCESS_TOKEN=your-secret-access-token
Note: Never commit your .env file to a repository! Always add .env to your .gitignore file.
We can use dotenv to load environment variables into our Node.js application. The following code demonstrates how to do this:
import { config } from "dotenv"; config({ path: "../../.env" }); // Define all required environment variables const envVars = { port: process.env.PORT || 5000, frontendUrl: process.env.FRONTEND_URL, nodeEnv: process.env.NODE_ENV as "development" | "production", dbConnect: process.env.DB_CONNECT, accessToken: process.env.ACCESS_TOKEN, }; /** * This function returns an environment variable and throws an error if unavailable. * @param varName - The key of the environment variable. * @returns The value of the specified environment variable. */ export default function getEnv(varName: keyof typeof envVars): string { if (typeof envVars[varName] === "undefined") { console.error(`'${varName}' is not available`); process.exit(1); } else { return envVars[varName] as string; } }
import { config } from "dotenv"; config({ path: "../../.env" });
This imports dotenv and loads the .env file into process.env.
const envVars = { port: process.env.PORT || 5000, frontendUrl: process.env.FRONTEND_URL, nodeEnv: process.env.NODE_ENV as "development" | "production", dbConnect: process.env.DB_CONNECT, accessToken: process.env.ACCESS_TOKEN, };
We define a set of expected environment variables and provide a default value for PORT in case it is missing.
export default function getEnv(varName: keyof typeof envVars): string { if (typeof envVars[varName] === "undefined") { console.error(`'${varName}' is not available`); process.exit(1); } else { return envVars[varName] as string; } }
This function ensures that if an environment variable is missing, the application will throw an error and terminate instead of failing silently.
Now, whenever we need an environment variable in our project, we can safely retrieve it like this:
import getEnv from "./getEnv"; const databaseURL = getEnv("dbConnect"); console.log("Database URL:", databaseURL);
If the variable is missing, the application will exit and log an error, ensuring we never run the app with missing configurations.
Managing environment variables is an essential part of application development, and the dotenv package makes it easy to load them securely. By creating a structured approach using a getEnv function, we can ensure that all required variables are properly loaded, preventing runtime errors caused by missing configurations.
By following best practices, we can enhance the security, maintainability, and flexibility of our Node.js applications.
npm install dotenv
The above is the detailed content of Managing Environment Variables in Node.js with dotenv. For more information, please follow other related articles on the PHP Chinese website!