Initialization of the App Object
The core of an Express application is the app object, which is essentially an enhanced instance of express.Router. The app object provides numerous methods for configuring middleware, routes, view engines, and more, along with global variables and error-handling mechanisms.
When creating a new Express application, you typically do the following:
const express = require('express');
const app = express();In this code, express() invokes the express.Application constructor, which creates an Application instance that inherits from Router. The Application is a constructor exported by the express module, encompassing all Router functionalities while adding extra methods and properties.
The initialization process of Application involves the following key steps:
- Creating a Router Instance: The
Applicationconstructor first creates aRouterinstance and assigns it to the_routerproperty. - Setting Default Middleware: The
Applicationcalls several methods in its constructor to set up default middleware, such asexpress.json()andexpress.urlencoded(), which parse JSON and URL-encoded request bodies, respectively. - Setting Default Error Handler: The
Applicationalso configures a default error-handling middleware to catch and process any errors that occur during request handling.
Working Principle of the Router Object
The Router is the module in Express used to define routes, supporting various HTTP methods and path matching. The working principle of Router can be summarized in the following steps:
- Registering Routes: When you use methods like
app.get(),app.post(),app.put(), orapp.delete(), you are adding route handlers to theRouter. These methods ultimately call theRouter’sroute()method, passing in the path and callback functions. - Path Matching: When a request arrives, the
Routermatches the request’s HTTP method and path against registered routes. Paths can include static segments and dynamic segments (i.e., parameters). - Executing Middleware and Route Handlers: Once a matching route is found, the
Routerexecutes the corresponding middleware and route handlers in the order they were registered. If a middleware or handler callsnext(), control passes to the next middleware or handler. - Sending Response: When a middleware or handler invokes response methods like
res.send(),res.json(), orres.render(), the response is sent to the client, concluding the request handling process.
The core of the Router is the _dispatch() method, which handles requests and responses. The _dispatch() method iterates through all registered routes, attempting to find a matching route and execute its handlers. If an error occurs during processing, _dispatch() calls the handle_error() method to manage the error.
Additionally, the Router uses the _findRoute() method to locate matching routes and the _parseParams() method to parse parameters in the path.
Middleware Execution Order and Stack Management
Types of Middleware
Express middleware can be broadly categorized into three types:
- Application-Level Middleware: Added via
app.use(), applicable to all requests. - Route-Level Middleware: Added via
app.get(),app.post(),app.put(),app.delete(), etc., applicable only to specific HTTP methods and paths. - Error-Handling Middleware: Specifically designed to handle errors during request processing, requiring a four-parameter function.
Middleware Execution Order
Middleware execution follows these rules:
- Execution by Registration Order: Middleware executes in the order it was added, with earlier middleware running first.
- Route Priority: When a request arrives, Express first looks for route-specific middleware matching the request method and path before executing application-level middleware.
- Error Handling Last: Error-handling middleware always executes last, regardless of where an error occurs in the middleware or route handlers.
Stack Management
Express uses an internal stack to manage the middleware execution flow. When a request arrives, Express starts executing middleware from the top of the stack until it finds a matching route or encounters a next('route') call. If a middleware calls next(), control passes to the next middleware or route handler.
Implementation of app.get(), app.post(), and app.use()
Let’s analyze how these methods are implemented by examining the source code.
function Application() {
// ...
this._router = new Router();
// ...
}
Application.prototype.use = function(path, fn) {
if (typeof path !== 'string') {
fn = path;
path = '/';
}
debug('use %s', path);
var router = this._router;
router.use(path, fn);
return this;
};In the app.use() method, it delegates to this._router.use(), where _router is the Router instance mentioned earlier.
Router.prototype.use = function(path, fn) {
// ...
this.stack.push(layer);
return this;
};The Router.prototype.use() method pushes the middleware into the stack, where stack is used to manage the middleware execution flow.
For methods like app.get() and app.post(), they ultimately call Router.prototype.route():
Application.prototype.get = function(path, ...fns) {
return this.route(path).get(...fns);
};
Router.prototype.route = function(path) {
var route = new Route(path);
this._routerCaseSensitive = this._routerCaseSensitive || route.isCaseSensitive();
this._routerStrict = this._routerStrict && !route.isPrefixOnly();
this.stack.push(route);
return route;
};In Router.prototype.route(), a new Route instance is created and pushed into the stack. Then, methods like route.get() or route.post() are used to add handlers for specific HTTP methods.
Route.prototype.get = function(fn) {
return this.method('GET', fn);
};
Route.prototype.method = function(method, fn) {
var layer = new Layer(fn);
layer.method = method;
this.stack.push(layer);
return this;
};In Route.prototype.method(), a Layer instance is created and pushed into the Route’s stack. This Layer instance contains the HTTP method and the corresponding handler function.
Route Matching Algorithm
Route Matching Algorithm
Express’s route matching algorithm relies on the path-to-regexp module, a tool for parsing and matching URL paths. Express uses path-to-regexp to convert route strings into regular expressions, enabling efficient matching of request URLs.
Route Object
In Express, each route is an instance of a Route object. The Route object stores all handlers for a specific path, including middleware and request handlers. When a request arrives, Express iterates through the Route object’s stack to find matching handlers.
class Route {
constructor(path) {
this.path = path;
this.stack = [];
this.methods = {};
this.regexp = pathToRegexp(path, this.keys, this.options);
}
get(path, ...fns) {
this.stack.push({ handle: createHandler(fns), method: 'GET' });
return this;
}
post(path, ...fns) {
this.stack.push({ handle: createHandler(fns), method: 'POST' });
return this;
}
// Other HTTP methods follow a similar pattern
}Route Matching Process
When a request arrives, Express iterates through all Route objects, using each Route’s regexp to match the request URL. If a match is found, Express executes the corresponding handlers.
function match(req, res, next) {
for (let i = 0; i < this.stack.length; i++) {
const layer = this.stack[i];
if (layer.method === req.method || layer.method === 'ALL') {
layer.handle(req, res, next);
return;
}
}
next();
}Extensions to Request and Response Objects
Express extends the native http.IncomingMessage and http.ServerResponse objects, providing richer functionality. For example, the req object is augmented with properties like params, query, and body, while the res object gains methods like send, json, and render.
// Extensions to the req object
req.params = {};
req.query = querystring.parse(req.url.split('?')[1]);
req.body = {};
// Extensions to the res object
res.send = function(body) {
this.setHeader('Content-Length', Buffer.byteLength(body));
this.end(body);
};
res.json = function(obj) {
this.setHeader('Content-Type', 'application/json');
this.send(JSON.stringify(obj));
};
res.render = function(view, options, callback) {
// Logic for rendering views
};



