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:

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

For Apache:

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

For Express:

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

Option 2: Using the Meta Tag

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

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