Essential CSP Directives
CSP directives control different types of content. Understanding each directive is crucial for implementing effective Content Security Policy.
default-src
default-src 'self';
The fallback directive for all other directives. If a specific directive isn't defined, the browser uses this one. This should be your most restrictive policy.
script-src
script-src 'self' 'nonce-{random}' 'strict-dynamic' https://trusted-cdn.com;
Controls which JavaScript sources can be executed. This is one of the most important directives for preventing XSS attacks. You can allow specific domains, use nonces, or hashes.
style-src
style-src 'self' 'nonce-{random}' https://fonts.googleapis.com;
Controls which CSS sources can be applied to your page. Similar to script-src but for stylesheets.
img-src
img-src 'self' data: https: blob:;
Controls which image sources are allowed. This includes images, icons, and other visual content.
font-src
font-src 'self' https://fonts.gstatic.com;
Controls which font sources are allowed. Important for web fonts and icon fonts.
connect-src
connect-src 'self' https://api.example.com wss://realtime.example.com;
Controls which URLs the page can connect to via XMLHttpRequest, WebSocket, EventSource, etc.
media-src
media-src 'self' https://media.example.com;
Controls which media sources are allowed (audio, video, etc.).
object-src
object-src 'none';
Controls which object, embed, and applet sources are allowed. Often set to 'none' for security.
frame-src
frame-src 'self' https://trusted-iframe.com;
Controls which frame sources are allowed. Deprecated in favor of child-src.
child-src
child-src 'self' https://trusted-embed.com;
Controls which sources can be embedded as frames and workers.
worker-src
worker-src 'self' blob:;
Controls which sources can be used as web workers.
manifest-src
manifest-src 'self';
Controls which manifest sources are allowed for web app manifests.
form-action
form-action 'self' https://secure-payment.com;
Controls which URLs can be used as form action targets.
base-uri
base-uri 'self';
Controls which URLs can be used as base elements.
Special Keywords
CSP includes several special keywords for common use cases:
Common Keywords
- 'self' - Same origin as the document
- 'unsafe-inline' - Allows inline scripts/styles (use with caution)
- 'unsafe-eval' - Allows eval() and similar functions (avoid if possible)
- 'none' - Blocks all sources
- 'strict-dynamic' - Allows scripts loaded by nonce/hash scripts
- data: - Allows data URLs
- blob: - Allows blob URLs
- https: - Allows any HTTPS source