Node.js + Express.js

Mental Model: Node.js is the runtime — it gives JavaScript access to the OS (files, network, processes). Express.js is a thin layer on top that adds routing and middleware. Everything else — architecture, validation, auth, error handling, security — is your responsibility to build correctly. This freedom is Express's biggest strength and biggest trap.


Node.js Core — Runtime Fundamentals

Skill Core Concepts & Mental Model Key Techniques Tradeoffs & Failure Modes Resources
Event Loop Node.js is single-threaded but handles thousands of concurrent connections via non-blocking I/O. The event loop runs in phases: Timers (setTimeout/setInterval) → I/O callbacks → Poll (wait for I/O) → Check (setImmediate) → Close callbacks. I/O is delegated to libuv thread pool (OS) — the JS thread never waits process.nextTick() (runs before next loop iteration — use sparingly), setImmediate() (runs in Check phase), queueMicrotask() (Promises — runs after current operation, before next phase) ❌ CPU-bound code (loops, crypto, image processing) blocks the event loop and stalls all concurrent requests. Never do heavy computation in a route handler — offload to worker_threads or a job queue Node.js Event Loop official, libuv docs
Modules — CJS vs ESM Two module systems exist. CommonJS (CJS): require()/module.exports — synchronous, dynamic. ES Modules (ESM): import/export — static, async, tree-shakeable. Node.js supports both but mixing them causes friction CJS: module.exports = { fn } / const { fn } = require('./module'). ESM: export const fn = ... / import { fn } from './module.js' (.js extension required). "type": "module" in package.json enables ESM globally ❌ Cannot require() an ESM module (use dynamic import() instead). Cannot use __dirname/__filename in ESM — use import.meta.url + fileURLToPath. Most npm packages are still CJS — check compatibility before switching project to ESM Node.js ESM docs
Async Patterns Three generations: callbacks → Promises → async/await. async/await is syntactic sugar over Promises — understand Promises to debug async/await. Node.js core APIs mostly use callbacks — promisify them util.promisify(fs.readFile), Promise.all() (parallel — all must succeed), Promise.allSettled() (parallel — don't fail-fast), Promise.race() (first to resolve/reject wins), Promise.any() (first to resolve wins) ❌ await inside a for loop = sequential (one at a time). Use Promise.all(array.map(async item => ...)) for parallel. Unhandled promise rejections crash the process in Node.js 15+ — always handle .catch() or use try/catch with await MDN Promises
Streams Process data piece-by-piece (chunks) without loading everything into memory. Four types: Readable (data source), Writable (data sink), Duplex (both), Transform (modify data in transit). Fundamental for file uploads, downloads, CSV processing, HTTP responses fs.createReadStream(), fs.createWriteStream(), .pipe(), stream.pipeline() (handles errors + cleanup — prefer over .pipe()), Transform stream for data transformation, readline for line-by-line file processing ❌ .pipe() doesn't propagate errors — use stream.pipeline() instead. Backpressure: if consumer is slower than producer, buffer fills up → memory leak. Check writable.write() return value — false means pause reading Node.js Streams, stream.pipeline
Worker Threads Run CPU-intensive JavaScript in a separate thread — doesn't block the event loop. Workers share ArrayBuffer (zero-copy via SharedArrayBuffer/Atomics) or communicate via postMessage (copy) const worker = new Worker('./worker.js'), worker.postMessage(data), parentPort.on('message', ...), workerData for initial data, thread pool pattern for reusing workers ❌ Worker threads are expensive to spawn — pool them (use workerpool or piscina library). Workers don't share memory by default (message passing = serialization overhead). Not for I/O-bound work — event loop handles that already Node.js Worker Threads, Piscina
Child Processes Run a separate process (shell command, Python script, another binary). Four methods: spawn (stream output), exec (buffer output), execFile (safer — no shell), fork (Node.js specific, IPC channel) spawn('ffmpeg', ['-i', input, output]) for long-running processes with streamed output. exec('ls -la', callback) for short commands. execFile to avoid shell injection. fork('./worker.js') for Node sub-processes with IPC ❌ exec() with user input = shell injection vulnerability — always use spawn/execFile with args array. exec() buffers all output in memory — use spawn for large output. Child process crash doesn't automatically crash parent — handle exit/error events Node.js Child Processes
File System (fs) Read/write files, directories, and file metadata. Two styles: callback-based (fs) and Promise-based (fs/promises). Always use fs/promises with async/await in modern code fs/promises: readFile, writeFile, appendFile, mkdir({ recursive: true }), readdir, stat, rename, unlink. Watch for changes: fs.watch(). Stream large files: createReadStream/createWriteStream ❌ fs.readFileSync() / fs.writeFileSync() block the event loop — never use in production request handlers (only CLI scripts). fs.watch() fires events twice on some OS (debounce it). Always handle ENOENT (file not found) and EACCES (permission denied) errors Node.js fs/promises
Environment & Config Never hardcode secrets or environment-specific values. Use process.env for config. Validate all env vars at startup — crash early if required vars are missing .env file + dotenv (local dev). process.env.NODE_ENV (development/production/test). Validate with Zod at startup: const config = z.object({ DATABASE_URL: z.string().url(), PORT: z.coerce.number() }).parse(process.env) ❌ Committing .env files to git = credential leak (use .gitignore). process.env values are always strings — parse numbers/booleans explicitly. No startup validation = mysterious runtime errors when env var is missing in production dotenv
Process Management Handle process lifecycle: graceful startup, graceful shutdown, signal handling, and crash recovery process.on('SIGTERM', gracefulShutdown), process.on('SIGINT', gracefulShutdown), process.on('unhandledRejection', (reason) => { logger.error(reason); process.exit(1) }), process.on('uncaughtException', ...) ❌ No uncaughtException handler = process crashes silently. No graceful shutdown = in-flight requests dropped when container restarts. uncaughtException should log + exit — not swallow the error. PM2/Docker will restart the process after crash Node.js Process

Express.js — Core

Skill Core Concepts & Mental Model Key Techniques Tradeoffs & Failure Modes Resources
Application Setup express() creates the app object. It is just a request handler function — you can pass it to http.createServer(app) or call app.listen(). Order matters: middleware and routes registered first are executed first const app = express(), app.use(express.json()) (parse JSON body), app.use(express.urlencoded({ extended: true })) (parse form data), app.use(cors()), app.use(helmet()), app.listen(PORT, () => console.log(...)) ❌ express.json() missing = req.body is undefined. Route order matters — a catch-all app.get('*', ...) before specific routes will swallow them. app.listen() returns an http.Server — save it for graceful shutdown Express.js Getting Started
Routing Map URL + HTTP method to a handler function. app.get/post/put/patch/delete. Express Router() creates mini-applications — group related routes and mount them on the main app app.get('/users/:id', handler), app.route('/users').get(list).post(create), express.Router() for modular routes, router.param('id', middleware) for param pre-processing, route parameters (req.params), query strings (req.query) ❌ app.get('/users/:id') will match before app.get('/users/me') if registered first — specific routes must come before parameterized ones. Missing return after res.send() = "headers already sent" error if code continues Express Routing
Middleware Functions that have access to req, res, and next. The entire Express request lifecycle is a middleware chain. Each middleware either ends the request (res.send()) or passes to the next (next()) Application-level: app.use(middleware). Router-level: router.use(middleware). Built-in: express.json(), express.static(). Third-party: cors, helmet, morgan. Error middleware: 4 params (err, req, res, next) — must be last ❌ Forgetting to call next() = request hangs forever. next(err) skips to error middleware. next('route') skips to next route. Middleware order is execution order — put helmet() and cors() first, error handler last Express Middleware Guide
Request Object (req) Represents the incoming HTTP request. Contains parsed body, URL params, query string, headers, cookies, and IP req.body (parsed body — needs express.json()), req.params (URL segments), req.query (query string), req.headers, req.method, req.path, req.ip (client IP — set trust proxy behind load balancer), req.cookies (needs cookie-parser) ❌ req.ip returns load balancer IP without app.set('trust proxy', 1). req.body is {} if Content-Type header is wrong. req.query values are always strings — parse numbers explicitly —
Response Object (res) Represents the outgoing HTTP response. Use one send method per request — calling two throws "headers already sent" res.json(data), res.status(201).json(data), res.send(text), res.sendFile(path), res.redirect(url), res.set('Header', 'value'), res.cookie(name, value, options), res.download(path) (triggers browser download), streaming: readable.pipe(res) ❌ res.json() and res.send() both end the request — calling one after the other = "headers already sent" error. res.json() sets Content-Type: application/json automatically. Forgetting return res.json() = code continues executing after response is sent —
Static Files Serve static assets (HTML, CSS, JS, images) directly from Express without a separate web server. For production, NGINX or a CDN should serve static files instead — much faster app.use(express.static('public')), app.use('/static', express.static(path.join(__dirname, 'public'))), set cache headers: express.static('public', { maxAge: '1d' }) ❌ express.static in production adds unnecessary Node.js overhead — use NGINX or upload to S3/Cloudfront. path.join(__dirname, 'public') is safer than relative path (varies by where process is started from) —

Express.js — Request Lifecycle & Patterns