How do I prevent committing .env to Git?
Add .env to your .gitignore file. Also add .env.local and .env.*.local. If you accidentally committed .env, run git rm --cached .env, add it to .gitignore, and commit. Always create a .env.example with placeholder values for new developers.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in What Is dotenv and Why Use It in Node.js Environment Variable Management
dotenv is an npm package that loads environment variables from a .env file into process.env. Install with npm install dotenv, then call require('dotenv').config() at the top of your entry file. This keeps secrets like database URIs, JWT secrets, and API keys out of your code.
For security (never commit secrets to Git), configuration (different settings for dev/staging/prod), portability (same code runs everywhere with different .env files), 12-factor app compliance, and team collaboration (each developer has their own .env with local settings).
Configuration and secrets only: PORT, NODE_ENV, MONGODB_URI, JWT_SECRET, API keys (AWS, Stripe, etc.), email credentials, and client URLs. Don't put business logic, non-secret config that's the same everywhere, or large data. Use descriptive names like MONGODB_URI not DB.
Still have questions?
Browse all our FAQs or reach out to our support team
