Express.js Basics
In the previous chapters, you learned how to create a basic HTTP server using Node’s built-inhttp module. While powerful, it requires significant boilerplate code for real-world applications. This is where Express.js comes in.
The Problem with Raw HTTP
Using the built-inhttp module, even simple tasks become verbose:
Why Express.js?
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It’s the de facto standard for Node.js web development.What Express Solves
| Problem | Express Solution |
|---|---|
| Complex routing logic | Simple, declarative routing |
| Parsing request bodies | Built-in middleware |
| Managing middleware | Composable middleware chain |
| Error handling | Centralized error handlers |
| Serving static files | One-line configuration |
Express by the Numbers
- 29+ million weekly downloads on NPM
- Powers thousands of production applications
- Extensive ecosystem of middleware packages
- Battle-tested since 2010
Installation
Creating a Basic Server
Routing
Express makes routing much easier than the rawhttp module.
Middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle (next).
The Airport Security Analogy: Think of middleware like the checkpoints you pass through at an airport. Each checkpoint (middleware function) inspects something specific: one checks your ticket (authentication), another scans your bag (body parsing), another checks the no-fly list (authorization). Each checkpoint either lets you through to the next one (next()), or stops you and sends you back (res.status(403).send()). The order of checkpoints matters—you cannot board (reach the route handler) without passing through all of them first. This is exactly why the order in which you register middleware with app.use() is critical.
Creating Custom Middleware
Built-in Middleware
Express has built-in middleware for parsing body data.Serving Static Files
To serve static files such as images, CSS files, and JavaScript files, use theexpress.static built-in middleware function.
Summary
- Express.js simplifies server creation and routing—it is a thin wrapper around Node’s
httpmodule - Use
app.get(),app.post(), etc., for routing - Middleware executes code between request and response—order of
app.use()calls matters - Always call
next()in middleware unless you are sending a response - Error-handling middleware must have exactly 4 parameters
(err, req, res, next)and must be registered last express.json()parses JSON request bodiesexpress.static()serves static assets