Contact Us
Webflow Premium Partner Ehab Fayez
Back to Agent Skills
Security & Quality

Content Security Policy

Define Content Security Policy headers to prevent XSS, clickjacking, and other code injection attacks.

Claude Code Cursor Copilot Windsurf

Overview

Content Security Policy (CSP) is an HTTP response header that tells browsers which sources of content are allowed to load on a page. It is one of the most effective defenses against Cross-Site Scripting (XSS) attacks, as it prevents the execution of unauthorized scripts even if an attacker manages to inject them into the page.

CSP directives control loading of scripts, stylesheets, images, fonts, frames, and other resources. Key directives include script-src (JavaScript sources), style-src (CSS sources), img-src (image sources), connect-src (fetch/XHR targets), and default-src (fallback for unspecified types). The helmet.js library provides a convenient API for setting CSP headers in Express applications with sensible defaults.

Implementing CSP effectively requires understanding your application's resource loading patterns. Report-only mode allows you to test policies without breaking functionality by sending violation reports to a specified endpoint. Nonce-based CSP is recommended for inline scripts, where a unique cryptographic nonce is generated per request and added to both the CSP header and script tags.

Who Is This For?

  • Prevent XSS attacks by restricting script sources
  • Block mixed content by enforcing HTTPS resource loading
  • Set up CSP reporting to monitor policy violations
  • Implement nonce-based CSP for inline scripts in SSR apps

Installation

Setup for Claude Code
npm install helmet

Configuration

import helmet from "helmet"

app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'nonce-{NONCE}'"],
    styleSrc: ["'self'", "https://fonts.googleapis.com"],
    imgSrc: ["'self'", "data:", "https:"],
    connectSrc: ["'self'", "https://api.myapp.com"],
    fontSrc: ["'self'", "https://fonts.gstatic.com"],
    frameAncestors: ["'none'"],
    upgradeInsecureRequests: [],
  },
}))