Introduction to Express.js
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It's the de facto standard server framework for Node.js.
Learning Objectives
- Understand what Express.js is and its role in backend development
- Learn about the middleware architecture
- Understand routing and HTTP methods
- Recognize when Express is the right choice for your project
Why Express.js?
Minimal & Fast
Unopinionated framework with minimal overhead for maximum performance
Flexible
Use any database, template engine, or architecture pattern you prefer
Battle-Tested
Powers millions of applications with extensive middleware ecosystem
Express.js Core Concepts
Your First Express Server
Here's how simple it is to create a web server with Express:
javascriptconst express = require("express") const app = express() const PORT = 3000 // Define a route app.get("/", (req, res) => { res.send("Hello World!") }) // Start the server app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`) })
Key Insight
Express abstracts the complexity of Node.js's built-in HTTP module, making it incredibly easy to build web servers and APIs.
HTTP Methods and Routing
Express provides methods for all HTTP verbs:
GET - Retrieve Data
javascript
// Get all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// Get user by ID
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === req.params.id);
if (!user) return res.status(404).json({ error: 'Not found' });
res.json(user);
});Middleware Architecture
Middleware functions are the backbone of Express. They have access to the request, response, and the next middleware in the chain.
javascript// Custom logging middleware const logger = (req, res, next) => { console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`) next() // Pass control to next middleware } // Apply middleware app.use(logger) // Built-in middleware app.use(express.json()) // Parse JSON bodies app.use(express.urlencoded({ extended: true })) // Parse URL-encoded bodies app.use(express.static("public")) // Serve static files
Middleware Flow
Request→Middleware 1→Middleware 2→Route Handler→Response
Express vs Other Frameworks
| Feature | Express | Fastify | NestJS |
|---|---|---|---|
| Learning Curve | Easy | Easy | Moderate |
| Performance | Good | Excellent | Good |
| TypeScript | @types/express | Built-in | Native |
| Architecture | Minimal | Minimal | Opinionated |
| Ecosystem | Massive | Growing | Strong |
When to Use Express
Quick Start Example
Here's a complete Express API example:
javascriptconst express = require("express") const cors = require("cors") const helmet = require("helmet") const app = express() const PORT = process.env.PORT || 3000 // Middleware app.use(helmet()) // Security headers app.use(cors()) // Enable CORS app.use(express.json()) // Parse JSON // In-memory data store let todos = [ { id: 1, title: "Learn Express", completed: false }, { id: 2, title: "Build an API", completed: false }, ] // Routes app.get("/api/todos", (req, res) => { res.json(todos) }) app.get("/api/todos/:id", (req, res) => { const todo = todos.find((t) => t.id === parseInt(req.params.id)) if (!todo) return res.status(404).json({ error: "Todo not found" }) res.json(todo) }) app.post("/api/todos", (req, res) => { const todo = { id: todos.length + 1, title: req.body.title, completed: false, } todos.push(todo) res.status(201).json(todo) }) app.patch("/api/todos/:id", (req, res) => { const todo = todos.find((t) => t.id === parseInt(req.params.id)) if (!todo) return res.status(404).json({ error: "Todo not found" }) if (req.body.title) todo.title = req.body.title if (req.body.completed !== undefined) todo.completed = req.body.completed res.json(todo) }) app.delete("/api/todos/:id", (req, res) => { const index = todos.findIndex((t) => t.id === parseInt(req.params.id)) if (index === -1) return res.status(404).json({ error: "Todo not found" }) todos.splice(index, 1) res.status(204).send() }) // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack) res.status(500).json({ error: "Something went wrong!" }) }) // Start server app.listen(PORT, () => { console.log(`🚀 Server running at http://localhost:${PORT}`) })
Next Steps
Continue Learning
Now that you understand what Express.js is, let's set up your development environment and build your first Express server!
Next Lesson
Setting Up Express Development Environment
Additional Resources