CSP Directives and Syntax
What You'll Learn
You'll learn how to construct Content Security Policy headers using directives, values, and proper syntax to control what resources your web page can load.
The Structure of CSP
A Content Security Policy is delivered via an HTTP header (or meta tag) that contains directives. Each directive controls a specific type of resource or behavior, followed by a source list that defines where those resources can come from.
The basic syntax looks like:
Content-Security-Policy: directive1 source1 source2; directive2 source3; directive3
Notice the semicolons separate different directives, while spaces separate multiple sources within the same directive.
Common CSP Directives
Resource directives control where different content types can load from:
script-src— JavaScript files and inline scriptsstyle-src— CSS stylesheetsimg-src— Imagesfont-src— Font filesconnect-src— AJAX, WebSockets, fetch requestsdefault-src— Fallback for unspecified directives
Example policy:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; img-src *
This says: "By default, only load resources from my own origin. Scripts can come from my site or trusted.cdn.com. Images can load from anywhere."
Source Values
Common source values include:
'self'— Same origin only (note the quotes!)'none'— Block everythinghttps:— Any HTTPS URLdomain.com— Specific domain'unsafe-inline'— Allow inline scripts/styles (risky!)'unsafe-eval'— Allow eval() (dangerous!)
Think of CSP directives like security guards at different doors: each directive guards a specific entrance, and the source list is the approved guest list.
Key Takeaway: CSP policies consist of semicolon-separated directives, each specifying a resource type and space-separated allowed sources, forming a whitelist that browsers enforce to prevent unauthorized content loading.