Course contentsShow
← Node.js
Lesson 624 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Request Lifecycle Hooks

Trigger custom logic at specific phases of the request, such as initialization, processing, and teardown.

In this lesson, you will learn how to inject your own custom logic into the specific stages of a request's journey through your Node.js application.

Understanding Request Lifecycle Hooks

When a client sends a request to your server, it doesn't just hit your business logic instantly. It travels through a series of "phases"—from the moment the raw bytes arrive at the socket to the final moment the response is sent back. Request Lifecycle Hooks are dedicated points in time where you can "hook" into this flow to run your own code, such as logging, authentication, or cleanup tasks.

Think of these hooks like stations in an assembly line. At the "Initialization" station, you might prepare the request context; at the "Processing" station, you execute your routes; and at the "Teardown" station, you perform final cleanup, like closing temporary file handles or logging the total duration of the request.

Implementing Hooks

While middleware acts as a chain, lifecycle hooks are often tied to specific events triggered by the framework as it manages the request. By attaching logic to these events, you ensure your code runs exactly when needed, regardless of which route or controller handles the request.

Consider this conceptual implementation of a lifecycle listener:

// Hooking into the lifecycle phases
server.on('request:init', (req) => {
  req.startTime = Date.now();
  console.log('Phase: Initialization - Context prepared.');
});

server.on('request:teardown', (req, res) => {
  const duration = Date.now() - req.startTime;
  console.log(`Phase: Teardown - Request completed in ${duration}ms`);
});

By tapping into these moments, you decouple cross-cutting concerns (like performance monitoring) from your core route handlers. Instead of cluttering your business logic with start-timers and cleanup code, you define these tasks once as lifecycle hooks. This ensures your application handles every request uniformly, maintaining a clean separation between the "what" (the feature) and the "how" (the infrastructure management).

Key Takeaway: Request lifecycle hooks allow you to execute logic at defined stages of a request's journey—initialization, processing, and teardown—ensuring consistent system behavior without bloating your core business logic.