Skip to main content

Security fix

How to Add a Content-Security-Policy (CSP) Header

Add a CSP to block cross-site scripting (XSS) by controlling what resources can load.

Last updated by the SlapMyWeb team

Difficulty
Medium
Impact
High
Time
40 min

Before

# No Content-Security-Policy header

After

Content-Security-Policy: default-src 'self'; script-src 'self' https://www.googletagmanager.com; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'
Before and after code for: How to Add a Content-Security-Policy (CSP) Header

A Content-Security-Policy header tells the browser which sources of scripts, styles and images it may load, so injected code cannot run. List the domains your site really uses, ship the policy in report-only mode first, fix what it reports, then enforce it and tighten it as you remove inline scripts.

Why it matters

A Content-Security-Policy is the strongest defense against XSS: it tells the browser exactly which sources of scripts, styles and images to trust and blocks everything else. It is also a quality/trust signal.

How to fix it

  1. Inventory your sources

    List every domain you load scripts, styles, fonts, images and frames from (analytics, fonts, embeds).
  2. Start in report-only

    Ship Content-Security-Policy-Report-Only first to catch violations without breaking the site, then promote to enforcing.
  3. Tighten over time

    Remove unsafe-inline/unsafe-eval by moving to nonces/hashes once the basics work.

The code

Beforehttp
# No Content-Security-Policy header
Afterhttp
Content-Security-Policy: default-src 'self'; script-src 'self' https://www.googletagmanager.com; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'

On your platform

WordPress

Set the header via a security plugin or .htaccess. Test in report-only first: plugins inject inline scripts that a strict CSP will block.

Next.js

Define CSP in headers() or middleware; use a nonce for inline scripts.

Sources

Check your site with our free tool

CSP Header Generator

Check it free

Fixed that one.
Now find the rest.

A free audit puts every issue on your site into a fix plan, most urgent first, and links each one to its guide.

Run a free audit
First audit freeNo card neededLive scan progress