Express.js
Express is a minimal and flexible Node.js web application framework. It's the most popular Node.js framework and provides a thin layer of fundamental web application features without obscuring Node.js capabilities.
Key Features
- Minimal: Small core, extend with middleware
- Routing: Flexible route handling with parameters
- Middleware: Composable request processing pipeline
- Template engines: Support for Pug, EJS, Handlebars
- Static files: Built-in static file serving
Basic Example
const express = require('express');
const app = express();
// Middleware
app.use(express.json());
// Routes
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }]);
});
app.get('/api/users/:id', (req, res) => {
res.json({ id: req.params.id, name: 'Alice' });
});
app.post('/api/users', (req, res) => {
const user = req.body;
res.status(201).json(user);
});
// Start server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Middleware Pattern
// Logging middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.path}`);
next();
};
// Auth middleware
const authenticate = (req, res, next) => {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
req.user = verifyToken(token);
next();
};
// Error handling middleware
const errorHandler = (err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal Server Error' });
};
app.use(logger);
app.use('/api', authenticate);
app.use(errorHandler);
Popular Middleware
| Package | Purpose |
|---|---|
| cors | Cross-origin resource sharing |
| helmet | Security headers |
| compression | Gzip responses |
| morgan | HTTP request logging |
| express-validator | Input validation |
| passport | Authentication strategies |
What We Like
- Simplicity: Easy to learn, quick to build
- Flexibility: No opinions, use what you want
- Ecosystem: Vast middleware and plugin options
- Documentation: Extensive guides and examples
- Community: Largest Node.js framework community
What We Don't Like
- Minimal: Requires many decisions and additions
- Callback-based: Original API not async/await native
- No structure: Easy to create messy codebases
- Maintenance: Slow release cycle (though stable)
Express vs Alternatives
| Framework | Style | Best For |
|---|---|---|
| Express | Minimal | Flexibility, learning |
| Fastify | Performance | High-throughput APIs |
| NestJS | Opinionated | Enterprise, TypeScript |
| Koa | Modern | Cleaner async handling |
When to Use Express
- Learning Node.js web development
- Simple APIs and microservices
- Projects needing maximum flexibility
- Teams comfortable with Node.js patterns
For TypeScript-first enterprise applications, consider NestJS. For performance-critical APIs, consider Fastify.