Security Content Policies (CSP)
Content Security Policy (CSP)
Protect your website from script injections and malicious data. Use a CSP meta tag to tell the browser exactly which domains are allowed to run scripts or styles:Imagine a museum security guard standing at the door with a whitelist. If an artist or courier tries to bring in a painting, the guard checks the list. If their name is not on the list, they are turned away immediately, preventing unauthorized or fake items from being displayed.
A Content Security Policy (CSP) is a security layer configured via a meta tag. It tells the browser exactly which external domains are allowed to load scripts, images, or stylesheets on your webpage.
Why does it matter?
CSPs protect your site from Cross-Site Scripting (XSS) attacks. If a hacker finds a bug on your page and tries to inject a script to steal passwords, the browser will block the script from running because the hacker's domain is not on your CSP whitelist.How to write it
Add the CSP meta tag to your<head> container:
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
</head>
In this example:
default-src 'self' tells the browser to only allow assets loaded from your own domain.
๐ก๏ธ Content Security Policy Active
Common Mistakes
default-src 'self' but use Google Fonts or YouTube embeds on your page, the browser will block them! Make sure to whitelist third-party domains in your policy (e.g., default-src 'self' https://fonts.googleapis.com).Quick Reference
<meta http-equiv="Content-Security-Policy" content="..."> โ Triggers browser security rules whitelists.Your Task
In the `<head>`, create a `<meta>` tag with `http-equiv="Content-Security-Policy"` and `content="default-src 'self'"`.
index.html
Type code above to start the lesson.
Live Preview