DEV Community

desgh white
desgh white

Posted on

Content Security Policy for Sites That Embed Third-Party Widgets

A strict Content Security Policy breaks most third-party widgets on first deploy. Chat widgets, analytics, A/B testing scripts — they all inject inline styles, eval code, or load from domains you haven't whitelisted. The fix is not to disable CSP; it is to build it incrementally.

Start in report-only mode

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-reports
Enter fullscreen mode Exit fullscreen mode

Deploy this header and collect violation reports for a week. The reports tell you exactly which domains and inline patterns your page actually uses.

Build the allowlist from reports

# Parse CSP reports to extract unique violated directives and sources
violations = defaultdict(set)
for report in reports:
    d = report['csp-report']
    violations[d['violated-directive']].add(d['blocked-uri'])
Enter fullscreen mode Exit fullscreen mode

The output is your allowlist. Promote it to enforcing mode:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.widget.com; style-src 'self' 'unsafe-inline'
Enter fullscreen mode Exit fullscreen mode

Nonces for inline scripts

Instead of 'unsafe-inline' for scripts, generate a per-request nonce:

<script nonce="abc123">/* trusted inline code */</script>
Enter fullscreen mode Exit fullscreen mode
script-src 'nonce-abc123' 'strict-dynamic';
Enter fullscreen mode Exit fullscreen mode

A content-rich site like Madcasino that integrates multiple third-party services benefits from 'strict-dynamic' — it allows scripts loaded by trusted scripts without listing every subdomain.

Common pitfalls

  • Google Tag Manager needs 'unsafe-inline' for styles (it injects <style> tags). Accept this tradeoff or move styles to a separate file.
  • Some analytics scripts use eval(). Switching to their module version usually eliminates this.
  • WebSocket connections need connect-src wss://your.socket.server.

Takeaway

CSP is not a one-shot config. It is a living document that you build from real traffic, deploy in report-only, and promote to enforcing once violations drop to zero.

Top comments (0)