# CSP

> The CSP (Content Security Policy) is a security mechanism that controls which resources a page is allowed to load and execute.

## How do I set up a Content Security Policy (CSP)?

The mechanism configured with the `Content-Security-Policy` header that restricts the sources of scripts, styles, images and other resources. One of the main protections against XSS attacks.

- Topic: Security
- Type: technique

## Example

Wrong:

```http
Content-Security-Policy: default-src *; script-src * 'unsafe-inline' 'unsafe-eval'
```

Right:

```http
Content-Security-Policy: default-src 'self'; script-src 'nonce-rAnd0m123' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'self'
```

A per-response nonce with 'strict-dynamic' allows only your scripts, while the wildcard and 'unsafe-inline' allow injected ones.

## Common mistakes

- Adding 'unsafe-inline' to fix errors, which removes most XSS protection.

## Key points

- `script-src` has no 'unsafe-inline' or 'unsafe-eval' and uses nonces or hashes instead.
- Nonces are random and new on every response, not a fixed string.
- The policy sets `object-src 'none'` and `base-uri`, and `frame-ancestors` is sent as a header, not in a meta tag.
- A new policy is tested with `Content-Security-Policy-Report-Only` before enforcing.

## Interview questions

### Can I set CSP in a meta tag?

Yes, with `<meta http-equiv='Content-Security-Policy'>`, but `frame-ancestors`, `report-uri` and `sandbox` are ignored there, so a header is preferred.

### Nonce vs hash in CSP: which should I use?

Use nonces for pages rendered per request, and hashes for static pages where inline script content never changes.

### Why does CSP block my inline event handlers?

Attributes like `onclick` are inline scripts, and nonces do not apply to them. Move handlers into a script with `addEventListener`.

## Related cards

- [Trusted Types](https://wonderium.dev/web/trusted-types.md)
- [SRI](https://wonderium.dev/web/sri.md)
- [Reflected XSS](https://wonderium.dev/web/xss-reflected.md)
- [Clickjacking](https://wonderium.dev/web/clickjacking.md)
- [HTTP Header](https://wonderium.dev/web/http-header.md)

---

- Level: [Web Platform](https://wonderium.dev/web.md)
- HTML version: https://wonderium.dev/web/csp
- Last updated: 2026-11-25
