Content Security Policy and Supply-Chain Safety
Limit what scripts can run with CSP, verify third-party code with SRI, and keep dependencies from becoming an attack vector.
Advanced · about 3 hours · difficulty 4/5
Learn first: Cross-Site Scripting (XSS) Prevention, Package Managers
Even careful teams ship bugs, so defence in depth matters. A Content Security Policy tells the browser which sources of scripts, styles, images and connections are allowed, so an injected script is blocked even if an XSS bug slips through.
CSP basics
Sent as the Content-Security-Policy header:
default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self' https://images.example.com; connect-src 'self' https://api.example.com; frame-ancestors 'none'; object-src 'none'; base-uri 'self'
- Prefer a strict CSP with per-request nonces or hashes plus
'strict-dynamic'over long allowlists of domains. - Avoid
'unsafe-inline'and'unsafe-eval'for scripts; they defeat most of the protection. frame-ancestorsprevents clickjacking by controlling who may embed your site.- Roll out with
Content-Security-Policy-Report-Onlyand a reporting endpoint, fix violations, then enforce. - Frameworks such as Next.js document how to add nonces with middleware.
Subresource Integrity
When loading a script or stylesheet from a CDN, add an integrity hash and crossorigin attribute so the browser refuses a tampered file.
Dependency and supply-chain hygiene
- Your
node_modulesruns in your users' browsers. Keep dependencies few and reputable. - Commit the lockfile, use
npm ciin CI, and enable automated update and audit tools (Dependabot or Renovate,npm audit). - Be wary of typo-squatted packages and install scripts; review new dependencies before adding them.
- Keep third-party tags (analytics, chat) under control and load them from trusted origins.
Good enough to move on
You can write a working CSP for an app you deployed, test it in report-only mode, add SRI to a CDN script and set up automated dependency updates.
Key concepts
- CSP directives
- Nonces, hashes and strict-dynamic
- Report-only rollout
- frame-ancestors and clickjacking
- Subresource Integrity (SRI)
- Dependency auditing and updates
- Lockfiles and npm ci
Mini project
Add a nonce-based CSP to a Next.js or Vite app, deploy it in report-only mode, collect and fix violations, enforce it, and enable Dependabot or Renovate on the repository.
Check yourself
Why does adding 'unsafe-inline' to script-src largely defeat the purpose of a CSP?