← Back to all snippets
JAVASCRIPT

Implement Content Security Policy (CSP) in Node.js Express

Enhance web application security by implementing Content Security Policy (CSP) in Express.js using Helmet.js, restricting content sources to mitigate XSS attacks.

const express = require('express');
const helmet = require('helmet');
const app = express();
const port = 3000;

// Use Helmet.js to set various security headers, including CSP
app.use(helmet());

// Customize CSP to allow content only from trusted sources
app.use(
    helmet.contentSecurityPolicy({
        directives: {
            defaultSrc: ["'self'"], // Allow resources only from the same origin
            scriptSrc: ["'self'", 'https://trusted-scripts.com'], // Allow scripts from self and a trusted domain
            styleSrc: ["'self'", 'https://fonts.googleapis.com'], // Allow styles from self and Google Fonts
            imgSrc: ["'self'", 'data:', 'https://cdn.example.com'], // Allow images from self, data URIs, and a CDN
            fontSrc: ["'self'", 'https://fonts.gstatic.com'], // Allow fonts from self and Google Fonts CDN
            objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
            upgradeInsecureRequests: [], // Automatically rewrite HTTP requests to HTTPS
        },
    })
);

app.get('/', (req, res) => {
    res.send('<h1>Hello, Secured World!</h1><script>console.log("Internal script.");</script>');
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});
How it works: This snippet demonstrates how to enforce a Content Security Policy (CSP) in an Express.js application using the `helmet` middleware. CSP helps prevent various attacks, including Cross-Site Scripting (XSS), by explicitly whitelisting trusted sources for different types of content (scripts, styles, images, etc.). The `directives` object defines these allowed sources, and `helmet.contentSecurityPolicy()` generates the `Content-Security-Policy` HTTP header based on these rules, which browsers then enforce.

Need help integrating this into your project?

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

Hire DigitalCodeLabs