0
0
Node.jsframework~5 mins

Environment configuration in Node.js

Choose your learning style9 modes available
Introduction

Environment configuration helps your app know important settings like where to find a database or what port to use. It keeps these details separate from your code so you can change them easily.

When you want to run the same app on your computer and on a server but with different settings.
When you need to keep secret keys or passwords safe and not put them directly in your code.
When you want to change the app's behavior without changing the code, like switching between test and live modes.
When you want to share your code but keep your personal settings private.
When you want to easily update settings like API URLs or ports without redeploying the app.
Syntax
Node.js
require('dotenv').config();

const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;

Use a .env file to store environment variables as key=value pairs.

Call require('dotenv').config() at the start of your app to load these variables into process.env.

Examples
This file sets the port and database URL your app will use.
Node.js
# .env file
PORT=4000
DATABASE_URL=mongodb://localhost:27017/mydb
This code loads the environment variables and prints the port number.
Node.js
require('dotenv').config();

console.log(process.env.PORT);
This sets a default port if none is provided in the environment.
Node.js
const port = process.env.PORT || 3000;
console.log(`Server runs on port ${port}`);
Sample Program

This Node.js program loads environment variables from a .env file and prints a greeting with the port number. If the variables are missing, it uses default values.

Node.js
/*
Create a file named .env with:
PORT=5000
GREETING=Hello
*/

import dotenv from 'dotenv';
dotenv.config();

const port = process.env.PORT || 3000;
const greeting = process.env.GREETING || 'Hi';

console.log(`${greeting}, server is running on port ${port}`);
OutputSuccess
Important Notes

Never commit your .env file to public code repositories to keep secrets safe.

You can use different .env files for development, testing, and production environments.

Environment variables are always strings, so convert them if you need numbers or booleans.

Summary

Environment configuration separates settings from code for flexibility and security.

Use a .env file and the dotenv package to load variables into process.env.

Always provide defaults and keep secrets out of your code.