Content Security Policy and Trusted Types Tutorial
On this page
Learning Objective
Write a Content Security Policy that blocks injected scripts using nonces or hashes with strict-dynamic, restrict other resource types and framing, roll it out safely with report-only mode and violation reports, and use Trusted Types to lock down DOM XSS sinks so only reviewed code can assign to them.
Concept Explanation
Day 91's defenses prevent XSS bugs; Content Security Policy limits the damage when one slips through anyway. CSP is a response header, Content-Security-Policy, that tells the browser which sources of content the page is allowed to use. The most important directive is script-src. If the policy only allows scripts that carry a secret nonce generated fresh for each response, an injected script tag without the nonce simply does not run, and inline event handlers and javascript: URLs are blocked as well.
Older CSPs were allowlists of domains, such as script-src 'self' https://cdn.example.com. Research by Google found that the large majority of such policies could be bypassed, because allowed domains often host JSONP endpoints, old library versions or user content that attackers can use as script gadgets. The recommended approach today is a strict CSP based on nonces or hashes. Each script tag the server renders gets a nonce attribute matching the nonce in the header, or the policy lists the hashes of known inline scripts. Adding strict-dynamic lets scripts loaded by those trusted scripts run too, which keeps bundlers, loaders and tag managers working without listing domains. object-src 'none' and base-uri 'none' close two other common bypasses.
CSP covers more than scripts. frame-ancestors controls who may embed your page in a frame, replacing the older X-Frame-Options header and preventing clickjacking. form-action limits where forms can submit, connect-src limits fetch and WebSocket destinations, img-src and style-src limit other resources, and upgrade-insecure-requests upgrades HTTP subresource requests to HTTPS. Policies should be delivered as headers rather than meta tags, because frame-ancestors and reporting do not work in meta.
Rolling out a policy safely relies on report-only mode. The Content-Security-Policy-Report-Only header reports violations without blocking anything, sending them to an endpoint configured with report-to. Teams deploy the policy in report-only mode, collect violations from real traffic, fix legitimate sources, such as inline handlers that should become event listeners, and then switch to enforcement, keeping reporting on to detect regressions and attacks. Frameworks support nonces: Next.js and others can read a nonce from a request header set by middleware and apply it to their script tags.
Trusted Types extends CSP to DOM-based XSS. When the policy includes require-trusted-types-for 'script', the browser refuses to accept plain strings at dangerous sinks such as innerHTML, script src and eval-like APIs. Code must instead pass objects created by a named Trusted Types policy, a function where you sanitize or validate the value. That turns every sink into a choke point: all HTML insertion flows through a small number of reviewed policies, such as one that calls DOMPurify, and any new code that assigns a raw string to innerHTML throws an error instead of becoming a vulnerability. Trusted Types are supported in Chromium-based browsers, with other engines adding support, and are harmless where unsupported, so they can be adopted in report-only mode first.
| Directive or feature | Purpose | Recommended value |
|---|---|---|
| script-src with nonce | Only scripts with the per-response nonce run | 'nonce-{random}' 'strict-dynamic' |
| object-src | Block plugins | 'none' |
| base-uri | Prevent base tag hijacking | 'none' or 'self' |
| frame-ancestors | Prevent clickjacking | 'none' or 'self' |
| form-action | Limit form destinations | 'self' |
| Report-only header | Test without breaking | Before enforcing |
| report-to | Collect violation reports | Your reporting endpoint |
| require-trusted-types-for | Lock down DOM sinks | 'script' |
Worked Example: A Nonce-Based Strict CSP with Trusted Types
Middleware generates a nonce per request and sets the policy, first in report-only mode. A single Trusted Types policy is the only way HTML enters the DOM.
// middleware.ts: a fresh nonce for every response
export function middleware(req: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const csp = [
`script-src 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'`, // https: and 'unsafe-inline' are fallbacks for old browsers; nonce-aware browsers ignore them
`object-src 'none'`,
`base-uri 'none'`,
`frame-ancestors 'none'`,
`form-action 'self'`,
`require-trusted-types-for 'script'`,
`trusted-types app-html default`,
`report-to csp`,
].join('; ');
const headers = new Headers(req.headers);
headers.set('x-nonce', nonce); // the framework reads it for its scripts
const res = NextResponse.next({ request: { headers } });
res.headers.set('Content-Security-Policy-Report-Only', csp); // switch to enforcing after review
res.headers.set('Reporting-Endpoints', 'csp="https://example.com/csp-reports"');
return res;
}<!-- Server-rendered scripts carry the nonce; injected ones cannot know it -->
<script nonce="{{nonce}}" src="/assets/app-4f9a2c.js"></script>// trusted-types.ts: the only reviewed path from strings to HTML
import DOMPurify from 'dompurify';
export const appHtml = window.trustedTypes?.createPolicy('app-html', {
createHTML: (input: string) => DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: false }),
});
export function setSanitizedHtml(el: Element, html: string) {
el.innerHTML = (appHtml ? appHtml.createHTML(html) : DOMPurify.sanitize(html)) as unknown as string;
}
// Anywhere else: el.innerHTML = userString -> TypeError under enforcement, report under report-onlyAfter deploying in report-only mode, the reports show any inline handlers, third-party scripts or innerHTML assignments that would break. Once they are fixed and reports are quiet, the header name changes to Content-Security-Policy and the protection is enforced.
Real-World Examples
- Google's 2016 research paper "CSP Is Dead, Long Live CSP!" analyzed about 1.7 million hosts and found that 94.72 percent of policies with script restrictions could be trivially bypassed, which led to the nonce-based strict CSP with strict-dynamic that Google now deploys across many of its products.
- Google has reported that adopting Trusted Types across many of its applications nearly eliminated DOM-based XSS reports in those applications, because every dangerous sink assignment had to go through a small set of reviewed policies.
Review Questions & Answers
Allowlisted domains often host content an attacker can abuse, such as JSONP endpoints or outdated libraries, so most allowlist policies can be bypassed. A nonce is a fresh random value per response that injected scripts cannot know, so only scripts the server deliberately rendered can run.
It allows scripts that were loaded by an already trusted, nonced or hashed script to run as well, without listing their domains. This keeps module loaders, bundler chunks and tag managers working while still blocking injected scripts.
A policy that blocks something legitimate, such as an inline handler or a third-party script, breaks the site for users. Report-only mode sends violation reports without blocking, so the team can find and fix every legitimate source before enforcing.
With enforcement on, dangerous sinks such as innerHTML refuse plain strings and accept only objects created by named policies. All HTML insertion must pass through those reviewed policies, which sanitize or validate input, so a stray assignment of untrusted data throws an error instead of executing.