Skip to main content

Express.js Basics

In the previous chapters, you learned how to create a basic HTTP server using Node’s built-in http 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-in http module, even simple tasks become verbose:
This gets even more complex when you add routing, error handling, authentication, and other features.

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

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 raw http 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 the express.static built-in middleware function.

Summary

  • Express.js simplifies server creation and routing—it is a thin wrapper around Node’s http module
  • 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 bodies
  • express.static() serves static assets

Express Router

Organize routes into separate modules: routes/users.js
app.js

Error Handling Middleware

Request Object Deep Dive

Response Object Methods

Third-Party Middleware

Application Structure Best Practice