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

Audit Logging Middleware

Automatically record all state-changing requests to an immutable audit trail.

In this lesson, you will learn how to implement an "Audit Logging Middleware" to automatically create an immutable trail of state-changing operations within your Node.js application.

The Purpose of Audit Logging

While standard application logs help you debug errors (telemetry), audit logs are for accountability and compliance. An audit log proves who changed what and when. In a robust architecture, you must distinguish between read-only requests (like GET) and state-changing requests (like POST, PUT, PATCH, or DELETE). Audit logging middleware intercepts these specific requests to record the "before" and "after" state of your domain entities.

Implementation Strategy

Because we want to ensure these logs are immutable, we treat the audit trail as a write-only sink. Instead of cluttering your core business logic, the middleware acts as a silent observer. It extracts the request context (the user ID, the timestamp, and the action) and sends it to a secure, append-only storage service or database.

Here is a simplified pattern for an audit middleware:

const auditLogger = (req, res, next) => {
  const stateChangingMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];

  if (stateChangingMethods.includes(req.method)) {
    const auditEntry = {
      timestamp: new Date().toISOString(),
      user: req.user?.id, // Context propagated via request object
      action: req.method,
      resource: req.originalUrl,
      payload: req.body
    };

    // Forward to an immutable storage service (e.g., an audit DB or log aggregator)
    AuditService.record(auditEntry);
  }

  next();
};

Why This Matters

By placing this logic in middleware, you decouple the audit requirement from your service layer or controllers. This ensures that you don't accidentally forget to log a critical state change. Furthermore, because this runs within your request pipeline, you can easily correlate the audit entry with other telemetry or error logs using a unique request ID. Remember: if it isn't logged, it didn't happen from the perspective of an auditor.

Key Takeaway: Use audit logging middleware to automatically capture and secure state-changing actions, creating an immutable history of system activity that remains independent of your core business logic.