Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Environment Variables
interview

Q1. What are environment variables and why use them?
Environment variables are dynamic values that can affect the behavior of running processes. In Node.js, they're used to store configuration like database credentials, API keys, and port numbers. They keep sensitive data out of code, allow different configurations per environment (dev, test, prod), and follow the twelve-factor app methodology.

Q2. How do you access environment variables in Node.js?
Environment variables are available in process.env object. Example:
const port = process.env.PORT || 3000; const dbPassword = process.env.DB_PASSWORD;
. They're always strings. You can set them in the terminal: PORT=5000 node app.js, or use .env files for development.

Q3. How do you use .env files?
Create a .env file in your project root: PORT=3000 DB_URL=mongodb://localhost/mydb. Install dotenv package: npm install dotenv. In your app, require and configure:
require('dotenv').config()
. Now process.env has the variables. Never commit .env to version control - add to .gitignore.

Q4. What are best practices for environment variables?
Use uppercase names with underscores. Provide default values for non-sensitive config. Validate required variables at startup. Never hardcode secrets. Use different .env files for different environments (but avoid committing them). In production, set variables through your hosting platform's dashboard.

Q5. How do you handle environment variables in production?
On cloud platforms like Heroku, AWS, or DigitalOcean, you set environment variables through their dashboards or CLI. For Docker, use -e flags or env_file. For systemd services, use Environment directives. Never store production secrets in code or public repositories. Use secret management services for sensitive data.