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 – Content Security Policy (CSP | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 39 of 55

·HTML

Security – Content Security Policy (CSP)

9 min

Course progress71%

What you'll learn

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

5 points
  • Purpose of Content Security Policy (CSP) for XSS mitigation
  • Defining sources for scripts, styles, images, fonts, and other resources
  • Using hashes and nonces to allow specific inline code
  • Testing CSP with `Report‑Only` mode before enforcing it
  • Common mistakes (missing third‑party domains, using `unsafe-inline`)

Mitigating XSS with CSP

CSP is delivered via HTTP header or <meta> tag to restrict which resources can be loaded.

<meta http-equiv='Content-Security-Policy' content="default-src 'self'; img-src https://images.example.com; script-src 'self' 'sha256-abc123'; style-src 'self' https://fonts.googleapis.com;" />

Directive overview

  • default-src – Fallback for all resource types.
  • script-src, style-src, img-src, font-src, connect-src, media-src, object-src – Fine‑grain control.
  • Hashes ('sha256-…') or nonces ('nonce-…') allow specific inline scripts/styles.
  • report-uri / report-to – URLs where violation reports (JSON) are sent.

Reporting mode

  • Content-Security-Policy-Report-Only – Lets you monitor violations without blocking resources; ideal for testing.

Common pitfalls

  • Forgetting to whitelist required third‑party scripts (e.g., analytics, reCAPTCHA).
  • Using 'unsafe-inline' defeats CSP’s purpose; avoid it unless you have a strong reason and use nonces instead.
  • Not including upgrade-insecure-requests when a site serves mixed content.

Quick checklist for CSP

  1. CSP delivered via HTTP header (preferred) or <meta>? ✅
  2. default-src set to 'self'? ✅
  3. Third‑party domains explicitly allowed? ✅
  4. Inline scripts/styles protected with nonces/hashes? ✅
  5. Report‑Only mode used during rollout? ✅

Tip: Start with a permissive policy in Report‑Only mode, gather violation reports, then tighten the policy step‑by‑step.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonPerformance – Preload, Prefetch, and PreconnectContinue to lesson 40Final Project – Build an Accessible Portfolio SiteBack to HTML Course curriculum