Missing Content Security Policy Header Enables Script Injection
What Is This Vulnerability?
A Content Security Policy (CSP) header tells the browser which sources of scripts, styles, and other resources are trusted. Without a CSP, the browser will execute any inline script or load resources from any domain, making cross-site scripting (XSS) attacks far easier to exploit and far harder to contain.
Why It Happens
Adding a proper CSP requires auditing every script, style, image, and font source used by the application. This can be tedious for large apps with third-party widgets, analytics snippets, and CDN assets. Many teams skip it entirely or postpone it indefinitely because a misconfigured CSP can break legitimate functionality.
Example Code
const nextConfig = {
async headers() {
return [
{
source: "/(.*)",
headers: [
// No Content-Security-Policy header defined
{ key: "X-Frame-Options", value: "DENY" },
],
},
];
},
};
export default nextConfig;const nextConfig = {
async headers() {
return [
{
source: "/(.*)",
headers: [
{
key: "Content-Security-Policy",
value: [
"default-src 'self'",
"script-src 'self' 'nonce-{REQUEST_NONCE}'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"connect-src 'self' https://api.myapp.com",
"frame-ancestors 'none'",
].join("; "),
},
{ key: "X-Frame-Options", value: "DENY" },
],
},
];
},
};
export default nextConfig;How Hackers Exploit It
Without a CSP, an attacker who finds any XSS vector (reflected, stored, or DOM-based) can inject a script tag that loads a remote payload from their server. This payload can steal cookies, capture keystrokes, redirect users to phishing pages, or modify the DOM to harvest credentials.
How to Fix It
Start with a report-only CSP to discover which sources your app relies on. Gradually tighten the policy by specifying allowed sources for scripts, styles, images, and connections. Use nonce-based or hash-based script allowlisting instead of unsafe-inline. Deploy the enforcing header once the report-only phase shows no violations from legitimate sources.