Course contentsShow
← Node.js
Lesson 1663 of 1,98015. Logging, Observability, and MetricsFree lesson

Handling Sensitive Information in Logs

Apply sanitization middleware to automatically redact PII or credentials from logs before transmission.

In this lesson, you will learn how to implement an automated sanitization layer that intercepts log entries to redact PII and credentials before they ever reach your logging transport.

The Problem with "Post-Process" Redaction

When we log objects in Node.js—such as incoming request bodies or database responses—it is dangerously easy to accidentally persist raw user passwords, tokens, or emails into our log aggregation tools. While you could manually sanitize every logger.info() call, that approach is prone to human error. A robust, advanced approach uses middleware-style log transformation to strip sensitive data globally.

Implementing Sanitization Middleware

By hooking into your logging library's transport or formatter pipeline, you can define a "scrubbing" function that recursively traverses objects and masks keys containing sensitive patterns.

Here is an example of a simple sanitizer that acts as a filter before data is written to the output stream:

const SENSITIVE_KEYS = ['password', 'token', 'email', 'credit_card'];

function sanitize(obj) {
  return JSON.parse(JSON.stringify(obj, (key, value) => {
    if (SENSITIVE_KEYS.includes(key.toLowerCase())) {
      return '[REDACTED]';
    }
    return value;
  }));
}

// Applying this to a Winston or Pino logger:
logger.format = combine(
  format((info) => sanitize(info))(),
  format.json()
);

Why This Matters

By placing this logic inside your logging pipeline, you decouple the intent to log from the security requirement to redact. Developers can continue logging entire objects for debugging purposes without needing to remember to manually pick apart every field.

When your logs flow into your centralized aggregation system, they arrive already sanitized. This ensures that even if developers have read access to log monitoring tools, they are not inadvertently exposed to sensitive user data, keeping your application compliant with data protection standards.

Key Takeaway: Implement an automated sanitization function within your logging pipeline to recursively identify and redact sensitive keys, ensuring PII and credentials are never persisted to your log storage.