Security headers

How to fix: Content-Security-Policy header

A Content-Security-Policy (CSP) header tells the browser which sources it may load scripts, styles, images and frames from. Anything not on the list is blocked.

Not sure whether your site has this problem? Check it in seconds.

Why it matters

CSP is a second line of defence against cross-site scripting (XSS): even if an attacker manages to inject a script tag, the browser refuses to run it if its source isn't allowed. It does not replace fixing the underlying bug, and it can't prove your site is free of XSS.

How to check

Open your site, then browser DevTools → Network → click the main document → Response Headers, and look for Content-Security-Policy. Or run our free Security Headers checker.

How to fix it

Starter policy

Content-Security-Policy: default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'

Nginx

add_header Content-Security-Policy "default-src 'self'; img-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'" always;

Apache

Header always set Content-Security-Policy "default-src 'self'; img-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"

Next.js (next.config.ts)

const nextConfig = {
  async headers() {
    return [
      {
        source: "/:path*",
        headers: [{ key: "Content-Security-Policy", value: "default-src 'self'; img-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'" }],
      },
    ];
  },
};
export default nextConfig;

Common mistakes

Frequently asked questions

Will a CSP slow my site down?

No. It's a response header the browser evaluates; the cost is negligible.

Is a CSP with 'unsafe-inline' still worth having?

It still restricts frames, plugins, base URIs and where resources load from, but it offers much weaker XSS protection. Treat it as a first step and work toward nonces or hashes.

Related guides

Guidance is general. Test header and DNS changes on a staging copy first, and check your hosting provider's documentation for platform-specific steps.