Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. JavaScript Course

Lesson 31 of 55 · javascript

Security – XSS, CSP & Input Sanitisation

Duration: 11 mins

Common attacks:

  • Cross‑Site Scripting (XSS) – inject malicious script.
  • DOM‑based XSS – unsafe innerHTML/eval.

Mitigations:

  1. Escape user input before inserting into HTML (textContent, createTextNode).
  2. Deploy a Content Security Policy (CSP) to restrict script sources.
  3. Avoid eval, new Function, and string‑based setTimeout.

Example: CSP header (meta fallback)

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; object-src 'none';">

Sanitising HTML with DOMPurify

import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userHtml);
document.getElementById('output').innerHTML = clean;
Previous: Intro to TypeScript (Optional)Next: Progressive Enhancement & Graceful Degradation