Topic 38 of 55
Express.js Framework
Overview
Express.js is a minimal, fast, and unopinionated web framework built on top of Node's native `http` module. It drastically reduces the boilerplate code needed to build APIs and web servers by providing robust routing and middleware capabilities.
Syntax
javascript
// Native HTTP (Verbose, manual routing)
const server = http.createServer((req, res) => {
if (req.url === '/api' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
}
});
// Express.js (Clean, declarative routing)
const express = require('express');
const app = express();
// Express handles headers, stringification, and routing automatically
app.get('/api', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(3000);Common Pitfalls
- Express is unopinionated. It doesn't force a specific folder structure (like Next.js does). You are responsible for organizing your routes and controllers cleanly.
- Express does not handle asynchronous errors automatically in route handlers. If an `async` route throws an error, the app will crash unless you wrap it in a `try/catch` or use an async wrapper package.
Real-World Example
A complete, production-ready Express server initialization:
example
javascript
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const app = express();
// 1. Apply Global Middleware
app.use(helmet()); // Secures HTTP headers automatically
app.use(cors()); // Allows cross-origin requests from frontends
app.use(express.json()); // Automatically parses incoming JSON payloads
// 2. Define Routes
app.get('/health', (req, res) => res.status(200).send('OK'));
app.use('/users', require('./routes/users'));
// 3. Start Server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`🚀 Server running on http://localhost:${PORT}`);
});