← Back to all snippets
HTML

Implement Content Security Policy (CSP) via Meta Tag

Protect your web application from cross-site scripting (XSS) and data injection attacks by defining a strict Content Security Policy using an HTML meta tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- CRITICAL: Implement Content Security Policy for XSS protection -->
    <meta http-equiv="Content-Security-Policy" content="
        default-src 'self';
        script-src 'self' https://trusted-cdn.com;
        style-src 'self' 'unsafe-inline';
        img-src 'self' data: https://trusted-images.com;
        font-src 'self' https://fonts.gstatic.com;
        connect-src 'self' https://api.example.com;
        frame-ancestors 'none';
        form-action 'self';
        object-src 'none';
    ">
    <title>Secure Web Page</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Welcome</h1>
    <script src="script.js"></script>
</body>
</html>
How it works: This HTML snippet demonstrates how to implement a Content Security Policy (CSP) using a `<meta>` tag. A CSP is a security standard that helps prevent various types of attacks, including Cross-Site Scripting (XSS) and data injection. By defining directives like `default-src`, `script-src`, and `style-src`, you instruct the browser which resources are allowed to be loaded, executed, or rendered on your page, significantly reducing the attack surface. The `frame-ancestors 'none'` directive helps prevent clickjacking by disallowing the page from being embedded in iframes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs