Angular › Angular Security (XSS, Sanitization & CSP)

How would you safely display user generated HTML content, such as a rich text comment, without exposing your app to XSS attacks?

Advanced

Answer

You use a trusted sanitization library, like DOMPurify, to clean the HTML first, removing any dangerous scripts or unsafe attributes, before ever marking the result as trusted using Angular's DomSanitizer. This lets you safely support formatted content like bold text or links while blocking anything genuinely harmful.
import DOMPurify from 'dompurify';

getSafeComment(rawHtml: string) {
  const cleanHtml = DOMPurify.sanitize(rawHtml);
  return this.sanitizer.bypassSecurityTrustHtml(cleanHtml);
}
Real-world example A forum allows users to write formatted comments using basic HTML tags like bold and italics, safely cleaning every comment through DOMPurify before marking it as trusted, blocking any hidden malicious script a bad actor might try to sneak in.

Common follow-ups: What specific kinds of malicious content does a library like DOMPurify actually remove?;Is sanitizing on the server, in addition to the client, also recommended for extra safety?