Content Security Policy for Static Sites

Content Security Policy for Static Sites

The Lesson

A Content Security Policy (CSP) is achievable on a static site without server-side headers by using a <meta> tag. The challenge is crafting a policy that's strict enough to block XSS but permissive enough to allow legitimate functionality — especially ES module imports from CDNs and inline styles from design system tokens.

Context

The quiz application renders user-facing content from JSON data files using innerHTML. A code review identified this as an XSS vector. The remediation was two-fold: (1) sanitize HTML before insertion, (2) add CSP as a defense-in-depth layer.

What Happened

A CSP meta tag was added to quiz.html and results.html:

<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; 
               script-src 'self' https://esm.sh; 
               connect-src 'self' https://esm.sh; 
               style-src 'self' 'unsafe-inline'; 
               img-src 'self' data:;">

Key Insights

Related Lessons