Content Security Policy
Define Content Security Policy headers to prevent XSS, clickjacking, and other code injection attacks.
Overview
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
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: [],
},
})) Explore AI Tools
Discover the best AI tools that complement your skills
Read AI & Design Articles
Tips and trends in the world of design and AI
Related Servers
Snyk Security Scan
Detect vulnerabilities in your dependencies and application code. Get actionable remediation advice and automatic fix pull requests.
SonarQube Code Quality
Run continuous code quality and security analysis to catch bugs, code smells, and vulnerabilities before they reach production.
OWASP ZAP Security Testing
Perform automated web application security testing to find common vulnerabilities like XSS, injection flaws, and misconfigurations.