ReviseAlgo Logo

Security

Content Security Policy (CSP)

Master Content Security Policy (CSP) in JavaScript. Learn to configure safety headers, define script sources, and block inline code executions.

Last Updated: July 15, 2026 10 min read

1. Introduction

Content Security Policy (CSP) is an HTTP response header that restricts which dynamic resources (like scripts, styles, images, and fonts) the browser is allowed to load and execute for a given page.

2. Why It Matters

Even if your application has XSS vulnerabilities, a strong CSP acts as a second line of defense. By blocking inline scripts and limiting script execution to trusted domains, CSP prevents injected malicious scripts from executing, protecting your users.

3. Real-World Analogy

Think of a Corporate Office Visitor Guestlist Policy:

  • No Policy (Open Lobby): Anyone can enter, walk into offices, and deliver documents. An intruder can walk in and deliver a fake instruction sheet.
  • CSP Policy (Security Guard Checkpoint): The guard checks a whitelist of approved companies (e.g. only employees from "Google" or "Stripe" are allowed). Symmetrically, if an intruder sneaks in and tries to run a meeting (injects an inline script), the guard halts the meeting because they are not on the guestlist.

4. CSP Directives

A Content Security Policy is defined using directives inside the Content-Security-Policy header:

default-src: The fallback policy for resources not explicitly defined.
script-src: Restricts which scripts can execute. Setting it to 'self' allows scripts from the same origin but blocks inline script tags (like <script>alert()</script>) and eval() calls.
img-src: Restricts image loading sources.

5. Using Nonces for Inline Scripts

Sometimes you need to execute legitimate inline scripts. You can authorize specific inline scripts by assigning them a unique, cryptographically secure nonce (number used once) generated by the server on every request:

6. Practical Example

This Express backend configuration sets a strong Content Security Policy header on all outgoing responses:

7. Common Mistakes

  • Using 'unsafe-inline' inside script-src directives: Setting script-src 'self' 'unsafe-inline' allows all inline scripts to execute. This defeats the main purpose of CSP, leaving your application vulnerable to XSS attacks. Use nonces or hashes to authorize specific inline scripts instead.

8. Quick Quiz

Q1: What does setting a script-src directive to 'self' accomplish in a Content Security Policy?

A) It allows scripts to be loaded from any origin

B) It limits script execution to files hosted on the same domain and blocks all unauthorized inline scripts

Answer: B — Setting script-src to 'self' permits scripts from the same origin while blocking inline scripts and eval calls.

9. Scenario-Based Challenge

The Analytics Script Loader CSP Integration:

Your site lazy-loads Google Analytics: https://www.google-analytics.com/analytics.js. After enabling a default 'self' CSP, the analytics script is blocked. Modify the CSP directives header to authorize loading this specific analytics source safely.

10. Debugging Exercise

Explain why this inline event handler is blocked under a strict CSP, and how to fix it:

<!-- HTML file -->
<!-- Bug: inline event handlers are blocked by script-src 'self' CSP! -->
<button onclick="alert('Clicked!')">Click Me</button>
View Solution

Diagnosis: Inline event handlers (like onclick, onerror, or onload) are treated as inline scripts and are blocked under a strict CSP to prevent malicious script injection.

Fix: Bind event listeners dynamically inside an external JavaScript file instead:

<!-- HTML file -->
<button id="my-btn">Click Me</button>

<!-- app.js (external script file) --> document.getElementById('my-btn').addEventListener('click', () => { alert('Clicked!'); });

11. Interview Questions

🟢 Q1: How does a Content Security Policy mitigate XSS vulnerabilities?

Answer: Even if an attacker injects a malicious script tag (XSS), a strong CSP restricts script execution:
Blocks Inline Scripts: Injected tags (like <script>evil()</script>) are blocked unless they contain a valid, cryptographically secure server-generated nonce.
Restricts Script Sources: The browser will only load external scripts from explicitly whitelisted domains, blocking scripts hosted on attacker servers.
Blocks Dynamic Execution: Restricts the use of unsafe APIs (like eval() or new Function()) that execute string inputs as code.

12. Production Considerations

  • Report-Only Mode: When deploying CSP to an existing application, use the Content-Security-Policy-Report-Only header first. This runs the policy in the background, logging violations to a specified URL without blocking resources, allowing you to test and refine the policy before enforcing it.