With the rise of supply chain attacks targeting npm dependencies, client-side web application security is more critical than ever. Relying solely on framework sanitization is no longer sufficient to guarantee safety.

Implementing strict Content Security Policies (CSP), Cross-Origin Embedder Policies (COEP), and Trusted Types provides defense-in-depth against malicious third-party script execution and data theft.

Table of Contents

1. Implementing Strict Nonce-Based CSP

Avoid `unsafe-inline` or broad domain wildcard rules in your CSP HTTP headers. Instead, generate a cryptographically secure random nonce per HTTP request and require it on all inline script tags:

# Example Production Security Headers
Content-Security-Policy: default-src 'self'; script-src 'nonce-rAnd0mN0nc3Vavlue' 'strict-dynamic'; object-src 'none'; base-uri 'none'; require-trusted-types-for 'script';
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin

2. Preventing DOM-XSS with Trusted Types

Trusted Types lock down dangerous DOM sink APIs like `element.innerHTML` or `eval()`. By defining a global Trusted Types policy, the browser automatically blocks any un-sanitized string assignment to the DOM at the engine level.

3. Cross-Origin Security Headers (COOP & COEP)

To prevent side-channel attacks like Spectre and secure high-resolution browser timers (`performance.now()`), configure `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` to isolate your execution context.

Frequently Asked Questions

What is the difference between CORS and Content Security Policy (CSP)?

CORS controls which external domains are permitted to make cross-origin HTTP API requests to your server. CSP controls which resources (scripts, styles, images) the browser is allowed to execute and load on your client-side page.

How can I deploy a CSP without breaking existing production features?

Deploy your policy using the `Content-Security-Policy-Report-Only` HTTP header first. This causes the browser to log policy violations to a reporting endpoint without blocking scripts.