3 min read
•Question 5 of 62easyHow to manage environment variables in Node.js?
Best practices for handling environment variables.
What You'll Learn
- Accessing environment variables
- Using dotenv
- Best practices
Accessing Environment Variables
code.jsJavaScript
// Access via process.env
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV;
console.log(process.env); // All env variablesUsing dotenv
$ terminalBash
npm install dotenvcode.jsJavaScript
# .env file
PORT=3000
DATABASE_URL=mongodb://localhost:27017/mydb
JWT_SECRET=mysecretkey
NODE_ENV=developmentcode.jsJavaScript
// Load at app start
require('dotenv').config();
// Or with ES modules
import 'dotenv/config';
// Now access variables
const port = process.env.PORT;Validation with Joi/Zod
code.jsJavaScript
const Joi = require('joi');
const envSchema = Joi.object({
NODE_ENV: Joi.string().valid('development', 'production', 'test').required(),
PORT: Joi.number().default(3000),
DATABASE_URL: Joi.string().required(),
}).unknown();
const { error, value } = envSchema.validate(process.env);
if (error) {
throw new Error(`Config validation error: ${error.message}`);
}
module.exports = {
env: value.NODE_ENV,
port: value.PORT,
dbUrl: value.DATABASE_URL,
};Best Practices
- Never commit .env to git
- Use .env.example as template
- Validate env vars at startup
- Use different .env files per environment