How do I use environment variables in a Node.js project with dotenv?

PA Paula99 VE 📗 Student 👁 67 ⚑ Report Programming

I'm building an API with Express and need to store my database credentials without pushing them to GitHub. I've seen a lot of people use dotenv but I'm not clear on how to set it up properly so it works in both development and production.

1 answer

★ Best answer

Install dotenv with `npm install dotenv`, create a `.env` file in your project root with your variables (like `DB_PASSWORD=mypassword`), and in your app's entry point (index.js or app.js) add `require('dotenv').config()` at the top so it loads those variables into `process.env` before the rest of the code runs.

For production, you just set the environment variables directly on your server or hosting platform (Heroku, AWS, whatever you use) without needing the `.env` file, and make sure `.env` is in your `.gitignore` so it never gets pushed to GitHub.

Your answer

Log into answer.