Express.js — Express Setup & Environment Configuration
Welcome to Express.js — Express Setup & Environment Configuration in our Express.js Complete Masterclass! Set up an Express.js project with npm scripts, environment variables (dotenv), and automatic development restarts.
Setting up an Express application involves initializing `package.json`, installing dependencies (`express`, `dotenv`), setting up environment variables in `.env`, and configuring development scripts (`node --watch`) for hot-reloading during code updates.
- Master the underlying Node.js event loop mechanics for Express Setup & Environment Configuration.
- Implement non-blocking, asynchronous execution pipelines in compliance with production API standards.
- Enforce strict OWASP Top 10 API security guidelines and performance optimizations.
| Environment Tool | Command / Flag | Purpose |
|---|---|---|
| Node Watch Mode | `node --watch app.js` | Native automatic process restart on code change |
| Dotenv | `import 'dotenv/config'` | Loads `.env` file key-value pairs into `process.env` |
| Package Scripts | `npm run dev` | Standardized CLI execution alias in `package.json` |
import express from 'express';
import dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const ENV = process.env.NODE_ENV || 'development';
app.get('/config', (req, res) => {
res.json({ environment: ENV, port: PORT });
});
app.listen(PORT, () => {
console.log(`Server started in ${ENV} mode on port ${PORT}`);
});
// Robust Configuration Loader Pattern
import express from 'express';
import dotenv from 'dotenv';
dotenv.config();
const config = {
port: parseInt(process.env.PORT || '5000', 10),
env: process.env.NODE_ENV || 'development',
apiPrefix: process.env.API_PREFIX || '/api/v1'
};
const app = express();
app.get(`${config.apiPrefix}/info`, (req, res) => {
res.json({ status: 'active', config });
});
app.listen(config.port, () => {
console.log(`Application running on port ${config.port}`);
});
- Committing `.env` secret files directly into Git version control repositories.
- Hardcoding API secrets, database passwords, or port numbers directly in source code.
- Failing to provide sensible default fallback values for critical environment variables.
❓ Question: Why use `node --watch` instead of Nodemon?
Answer: Node.js 18.11+ includes native `--watch` functionality built directly into the runtime, reducing external third-party dependencies.
❓ Question: How do I prevent `.env` files from leaking into Git?
Answer: Add `.env` and `.env.local` entries to your project's `.gitignore` file before committing.
Create a `.env` file containing `PORT=4500` and `APP_TITLE=OurCompilerBackend`. Write an Express server that logs `APP_TITLE` on startup.