Content-Security-Policy (CSP) tells a browser which sources a page may use for scripts, images, stylesheets, media, and other resources. It limits what injected or remotely hosted code can run, making it a useful layer of defense against cross-site scripting (XSS). section 2.3 section 6.7
Send CSP in the HTTP Content-Security-Policy response header to apply a policy consistently across an application. A meta tag can express the same policy for a particular hardcoded page. For example, default-src 'self' permits resources only from the page's own origin, so a script hosted on another domain is blocked. section 2.3
const express = require("express")
const app = express()
const port = 3000
app.get("/", (req, res) => {
res.set("Content-Security-Policy", "default-src 'self'") #1
res.send("Web app secure!")
})
app.listen(port, () => {
console.log("Example app listening on port ${port}")
})
This Express handler sets default-src 'self', instructing the browser to load content only from the application's own source domain. section 2.3
Use directives to make resource rules as narrow as the page permits:
- Use default-src 'self' as a simple baseline that restricts unspecified resource types to the hosting domain. section 2.3
- Use script-src, img-src, and media-src when scripts, images, or media need different allowed sources. section 6.7
- Avoid 'unsafe-inline' when possible: inline JavaScript is a common XSS injection path, and allowing it explicitly weakens that protection. section 2.3 section 6.7
Blocking an injected script
If untrusted comment content contains an inline script, a policy that allows scripts only from breddit.com and does not include 'unsafe-inline' prevents that script from executing. CSP complements, rather than replaces, escaping dynamic content in templates. section 6.7
CSP also protects against clickjacking by controlling which sites may place a page in an iframe. frame-ancestors 'none' disallows framing entirely; 'self' permits only the same site; named trusted sites can be added when framing is required. section 6.13 section 6.18

