Skip to content

Content Security Policy

CSP

Medium — good to knowSecurity

ELI5 — The Vibe Check

Content Security Policy is an HTTP header that tells the browser exactly where it's allowed to load scripts, images, and other resources from. It's like a bouncer who only lets approved guests (trusted domains) provide scripts to the page. Even if an XSS attack injects a script tag, CSP can block it from running.

Real Talk

CSP (Content Security Policy) is an HTTP response header that instructs browsers to restrict resource loading to specified origins. It's a defense-in-depth measure against XSS attacks. Directives include script-src, style-src, img-src, connect-src, etc. Violations can be reported to a URI for monitoring.

Show Me The Code

// Setting CSP in Express
app.use((req, res, next) => {
  res.setHeader(
    'Content-Security-Policy',
    [
      "default-src 'self'",
      "script-src 'self' https://cdn.example.com",
      "style-src 'self' 'unsafe-inline'",
      "img-src 'self' data: https:",
      "report-uri /csp-violations",
    ].join('; ')
  );
  next();
});

When You'll Hear This

"Add a strict CSP header to reduce XSS risk." / "The CSP report showed a blocked inline script."

Made with passive-aggressive love by manoga.digital. Powered by Claude.