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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Security – XSS, CSP & Input Sanit | JavaScript Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. JavaScript Course

Lesson 31 of 55

·javascript

Security – XSS, CSP & Input Sanitisation

11 mins

Course progress56%

What you'll learn

Keep these ideas in mind as you work through the lesson.

3 points
  • `strict‑mode` (enabled automatically in modules) prevents accidental globals.
  • CSP is most effective when sent via **HTTP response headers**.
  • Always **validate** and **sanitize** any data that will be rendered as HTML.

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;
Make it stickPractice what you've learned1 quiz · 7 practical tests · Optional activities from JavaScript CourseBrowse activities
Previous lessonIntro to TypeScript (Optional)Continue to lesson 32Progressive Enhancement & Graceful DegradationBack to JavaScript Course curriculum