Content Security Policy (CSP) Implementation Guide: Protect Your Website from XSS Attacks
Published on April 26, 2025
I’d been living in backend land for so long that my frontend knowledge felt outdated. React Hooks were still considered the “latest big thing” in my view. I was so focused on making my blog functional that I overlooked whether it was safe.
The wake-up call came when I started researching web security best practices. That’s when I discovered CSP - a security feature I’d never heard of, designed to prevent cross-site scripting (XSS) attacks. The more I read, the more I realized I’d been building digital houses without locks.
Here’s the alarming part: XSS attacks are everywhere, and they’re getting more sophisticated. Even if you’re diligent about sanitizing user input (and let’s be honest, how many of us are really diligent?), one slip-up can compromise your entire site.
From MDN Web Docs:
Content Security Policy (CSP) is a feature that helps to prevent or minimize the risk of certain types of security threats. It consists of a series of instructions from a website to a browser, which instructs the browser to place restrictions on the things that the code comprising the site is allowed to do.
Without CSP, your website essentially says “yes” to everything. Malicious scripts can:
- Load external JavaScript from anywhere on the internet
- Execute inline scripts that bypass your security measures
- Hijack event handlers in your HTML
- Use dangerous APIs like
eval()to run arbitrary code
The worst part? These attacks often happen silently. Your users get compromised, your reputation takes a hit, and you might not even know it’s happening until it’s too late.
Think about it: every form, every comment section, and every piece of user-generated content is a potential entry point. One successful XSS attack can steal user data, hijack sessions, or turn your website into a base for further attacks.
Content Security Policy is like having a professional security guard for your website. It tells the browser exactly what’s allowed and what isn’t, creating a whitelist of trusted sources and behaviors.

Here’s how CSP transforms your security posture:
Script Control: Instead of allowing any script from anywhere, you specify exactly which domains can serve JavaScript to your site. Want to use Google Analytics? Add it to the list. Random script from evil.example.com? Blocked.
Inline Script Protection: CSP can completely disable inline scripts, forcing you to use external files or secure methods like nonces and hashes. This single change eliminates entire categories of XSS attacks.
Resource Restrictions: You can control where images, fonts, stylesheets, and other resources come from. This prevents attackers from loading malicious content that could compromise your site’s integrity.
Dangerous API Blocking: CSP can disable risky functions like eval(), setTimeout() with strings, and Function() constructors that are commonly exploited in attacks.
The beauty of CSP is that it works even when your other security measures fail. It’s your last line of defense, and often your most effective one.
My CSP Implementation Battle
Let me be brutally honest: implementing CSP on my Astro blog was humbling. It took me days to get it right, and I learned that CSP doesn’t just protect you - it also ruthlessly exposes every shortcut you’ve taken.
Astro Documentation: Content Security Policy
Here’s the configuration that finally worked for me:
experimental: {
csp: {
directives: [
"default-src 'self'",
"img-src 'self' data:",
"font-src 'self' https://fonts.gstatic.com",
"object-src 'none'",
"base-uri 'self'",
],
scriptDirective: {
resources: ["'self'", "https://static.cloudflareinsights.com"],
hashes: [],
},
styleDirective: {
resources: ["'self'", "https://fonts.googleapis.com"],
hashes: [],
},
},
},
Here’s what each piece does:
default-src 'self'- Only allow resources from your own domain by defaultimg-src 'self' data:- Allow images from your domain and data URIs (for inline images)font-src 'self' https://fonts.gstatic.com- Allow fonts from your domain and Google Fontsobject-src 'none'- Disable plugins like Flash (they’re security nightmares)base-uri 'self'- Prevent attackers from changing your document’s base URL
Pro tips from my struggle:
- Start permissive, then tighten: Begin with a loose policy and gradually restrict it as you identify what your site actually needs
- Use report-only mode first: CSP can report violations without blocking them, letting you test without breaking your site
- Hash your inline scripts: If you must use inline scripts, generate CSP hashes for them
- Monitor your console: CSP violations show up in the browser console - they’re your best debugging tool
Don’t make my mistake of treating security as an afterthought. Here’s how to implement CSP on your website without the days of frustration:
Step 1: Audit Your Current Setup
- Use browser developer tools to see what resources your site loads
- Check for inline scripts and styles
- Identify all external domains you’re using (fonts, analytics, CDNs)
Step 2: Start with Report-Only Mode
Add Content-Security-Policy-Report-Only header instead of Content-Security-Policy. This lets you test your policy without breaking anything.
Step 3: Build Your Policy Gradually
- Start with
default-src 'self' - Add specific directives for each resource type you need
- Test thoroughly after each change
Step 4: Generate Hashes for Inline Content Use tools like CSP hash generators for any inline scripts or styles you can’t eliminate.
Step 5: Monitor and Iterate Set up CSP violation reporting and regularly review what’s being blocked. Your security posture should evolve with your site.
The Bottom Line: CSP isn’t just another technical checkbox - it’s your website’s immune system. In a world where security breaches make headlines daily, implementing CSP is no longer optional. It’s the difference between being a security-conscious developer and being tomorrow’s cautionary tale.
Your users trust you with their data. CSP helps you deserve that trust. Don’t wait for a security incident to take action - implement CSP today, and sleep better knowing your digital bouncer is on duty.
Referenced by (1)
These are pages that link to this page.