Express.js Setup
Overview
Express.js is the absolute industry standard framework for Node.js. It is a 'Micro-Framework'—it doesn't force a database or folder structure on you like Django or Ruby on Rails. Instead, it provides a highly optimized, unopinionated routing engine and middleware pipeline, completely abstracting away the nightmare of parsing raw streams and building manual HTTP headers.
Syntax
// 1. Install it via NPM: $ npm install express
const express = require('express');
// 2. Initialize the Express Application
const app = express();
// 3. Define a Route (Method + Path)
app.get('/api/health', (req, res) => {
// Express provides magical helper methods!
// It automatically sets 'Content-Type: application/json'
// and calls res.end() for you!
res.status(200).json({ status: "Database is healthy!" });
});
// 4. Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Express API running on port ${PORT}`);
});Common Pitfalls
- Bloating
server.js. Beginners often put 50 routes, database connections, and business logic into one massiveapp.jsfile. Express does not enforce architecture. It is entirely up to you to implement modular design (usingexpress.Router()) to split routes into specialized controller files. - Forgetting that Express is fundamentally synchronous in its routing. If you define a route
app.get('/users'), and later down the file define a wildcardapp.get('*'), the routing is strictly Top-to-Bottom. If you put the wildcard at the top, it will intercept and hijack every single request, completely breaking the app.
Interview Questions
Unopinionated means Express does not care how you structure your code. It doesn't provide an ORM, a validation library, or a standardized folder architecture. You have to build the stack yourself. NestJS is 'Opinionated'; it forces you to use TypeScript, Dependency Injection, Controllers, and strict architectural modules out-of-the-box.
Real-World Example
Serving a static frontend (React build folder) using Express's native static file server.
const express = require('express');
const path = require('path');
const app = express();
// Automatically serve CSS, JS, and Images from the 'public' folder!
app.use(express.static(path.join(__dirname, 'public')));
app.listen(8080);Check Your Knowledge
Test your understanding of Express.js Setup with these quick questions.