JavaScript Interview Question #140

What is Content Security Policy (CSP)?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

Content Security Policy is a browser security mechanism controlled through HTTP response headers or, in some cases, a meta element. It lets an application restrict where scripts, styles, images, frames, and other resources may be loaded from.

Detailed Explanation

Content Security Policy is a browser security mechanism controlled through HTTP response headers or, in some cases, a meta element. It lets an application restrict where scripts, styles, images, frames, and other resources may be loaded from.

A strong CSP can reduce the impact of certain injection vulnerabilities, especially XSS, but it is a defense-in-depth measure rather than a replacement for secure output handling. Production CSPs should be designed and tested carefully because overly broad directives reduce their protection.

Code Example

// Example HTTP response header configured by the server:
//
// Content-Security-Policy:
//   default-src 'self';
//   script-src 'self';
//
// Prefer configuring CSP as an HTTP response header
// in the web application's server/security configuration.