🚀 Express.js Intermediate

What is the dotenv package and how is it used in Express?

Answer

dotenv loads environment variables from a .env file into process.env, keeping sensitive configuration (database URLs, API keys, JWT secrets) out of source code. Install: npm install dotenv. At the very top of your entry file: require('dotenv').config();. Your .env file: DB_URL=mongodb://localhost/mydb\nJWT_SECRET=supersecret\nPORT=3000. Access: process.env.DB_URL. Add .env to .gitignore — never commit it. Provide a .env.example with placeholder values as documentation. In production (hosting platforms like Heroku, Render, AWS), set environment variables directly in the platform settings rather than a .env file.