We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

When to Sanitize

Of course, there are times when sanitization makes sense. For example, you might want to remove trailing and leading whitespace from the username input silently, as most users expect that behavior. But you still should have a validation step that rejects invalid ones.

For example, you might use it when:

  • Sanitizing rich text fields (comments, posts) that allow a limited set of formatting options like bold and italics
  • Removing unsupported control characters from text that will be stored or processed
  • Escaping characters that won't render correctly in your chosen output format (e.g., replacing \n with <br> in HTML)

Sanitize to a Policy

Here's a "create comment" endpoint that validates input, sanitizes it to a small allowlist of HTML tags, and saves it:

app.post("/comments", (req: Request, res: Response) => {
  const { content } = req.body;
  // validate: string, not too long
  if (typeof content !== "string" || content.length > 280) {
    return res.status(400).json({ error: "Invalid content" });
  }
  // sanitize: strip all tags except for bold and italics
  const sanitizedContent = sanitizeHtml(content, {
    allowedTags: ["b", "i", "em", "strong"],
    allowedAttributes: {},
  });
  // re-validate: not empty after sanitization
  if (sanitizedContent.trim().length === 0) {
    return res.status(400).json({ error: "Empty content" });
  }
  saveComment(sanitizedContent); // Error handling omitted for brevity
  res.status(201).json({ message: "Comment saved" });
});

Notice that validation happens first, and sanitization is tightly scoped.

Assignment

Bearly Secure validates review bodies, but preserves leading and trailing whitespace. Sanitize review text by trimming only its outer whitespace.

With Bearly Secure still running, run and submit the CLI tests from the project root.