Curriculum Series

What is content security policy (CSP)?

What is content security policy (CSP)?

What is content security policy (CSP)?

Security

Content Security Policy (CSP)

Content Security Policy (CSP) is a security feature that helps prevent various types of attacks, such as Cross-Site Scripting (XSS) and data injection attacks, by controlling which resources (scripts, styles, images, fonts, etc.) can be loaded and executed on a web page.

How to implement CSP?

Option 1: Using the HTTP Header (Recommended)

In your server configuration, add the Content-Security-Policy header.

For Nginx:

JAVASCRIPT
1add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://apis.google.com; style-src 'self' 'unsafe-inline';";

For Apache:

JAVASCRIPT
1Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://apis.google.com; style-src 'self' 'unsafe-inline';"

For Express:

JAVASCRIPT
1app.use((req, res, next) => {
2 res.setHeader(
3 'Content-Security-Policy',
4 "default-src 'self'; script-src 'self' https://apis.google.com; style-src 'self' 'unsafe-inline';"
5 );
6 next();
7});

Option 2: Using the Meta Tag

In your HTML file, add the Content-Security-Policy meta tag.

JAVASCRIPT
1<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://apis.google.com; style-src 'self' 'unsafe-inline';">

Finished reading?

Mark this topic as solved to track your progress.