In this lesson, you will learn how to use Content Security Policy (CSP) headers to restrict where your browser loads resources from, effectively neutralizing most client-side script injection attacks.
Understanding the Need for CSP
When a browser loads your web page, it is inherently trusting. If a malicious actor manages to inject a <script> tag into your HTML (a Cross-Site Scripting or XSS attack), the browser will happily execute that script. As a developer, you need a way to tell the browser: "Only execute scripts that come from my own domain, and ignore everything else."
This is where the Content-Security-Policy HTTP header comes in. By sending this header from your Node.js server, you define a whitelist of trusted sources.
Implementing the Header in Express
Since we are comfortable with the Middleware Pattern, we can easily enforce this policy globally by attaching the header to every response.
app.use((req, res, next) => {
// Only allow scripts from our own origin
res.setHeader(
"Content-Security-Policy",
"default-src 'self'; script-src 'self'; object-src 'none';"
);
next();
});
How it Works
In this example, the policy does three things:
default-src 'self': Sets a fallback for all content types (images, styles, etc.) to only load from your own domain.script-src 'self': Explicitly forbids inline scripts (like<script>alert(1)</script>) and scripts hosted on external third-party domains.object-src 'none': Disables plugins like Flash, which are frequent targets for exploits.
If an attacker tries to inject a script pointing to a malicious domain, the browser will block the request and report a violation in the developer console. This provides a robust "defense-in-depth" layer. Even if your code has a vulnerability that allows user input to be reflected on the page, the CSP acts as a final gatekeeper that prevents the malicious code from ever running.
Key Takeaway: A strict Content Security Policy acts as a browser-side firewall that prevents unauthorized scripts from executing, significantly reducing the impact of potential injection vulnerabilities.