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
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
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'])
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'
Nonces for inline scripts
Instead of 'unsafe-inline' for scripts, generate a per-request nonce:
<script nonce="abc123">/* trusted inline code */</script>
script-src 'nonce-abc123' 'strict-dynamic';
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.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.