DEV Community

Muhaymin Bin Mehmood
Muhaymin Bin Mehmood

Posted on Originally published at mbloging.com

Understanding Content Security Policy (CSP) in JavaScript Apps

Hey folks, let’s dive into Content Security Policy (CSP) — a powerful yet often misunderstood tool that helps you lock down where your app can load resources from, protecting against XSS, click‑jacking, and more.

🛡️ What is CSP?

CSP is a browser‐enforced set of rules—sent via HTTP headers (or tags)—that defines which sources your app can load scripts, stylesheets, images, frames, and other resources from

For example:

Content-Security-Policy: default-src 'self'; img-src 'self' example.com;
Enter fullscreen mode Exit fullscreen mode

This means:

By default, only load assets from the same origin
Images can also come from example.com

Why use CSP?

  1. Block XSS attacks – Restrict script sources so injected code can’t run
  2. Block click‑jacking – Prevent framing via frame-ancestors
  3. Enforce HTTPS – Use upgrade-insecure-requests to force secure loads
  4. Boost trust – Shows users you care about security

Common CSP directives

  • default-src – default fallback for everything
  • script-src, style-src, img-src, connect-src, etc. – control specific asset types
  • object-src 'none' – block Flash & plugins
  • frame-ancestors 'none' – prevent embedding (stronger than X-Frame-Options)

👉 Want to see the full breakdown with real‑world examples, error cases, and extra tips? Check out my original post on mbloging.com:

👉 Understanding Content Security Policy (CSP) in JavaScript Applications

Feel free to DM me if you want to chat more about CSP or need help implementing it!

Top comments (0)