Content Security Policy Middleware for Express

6.3.1 · active · verified Wed Apr 22

express-csp-header is an Express.js middleware designed to streamline the implementation of Content-Security-Policy (CSP) headers in web applications. It wraps the functionality of the `csp-header` package, providing an Express-specific interface. Currently at stable version 6.3.1, the package maintains an active release cadence, frequently releasing patches and minor features. Key differentiators include its integration with Express's middleware system, providing convenient constants like `SELF`, `INLINE`, `NONCE`, and `TLD` for dynamic policy generation. It also features automatic Top-Level Domain (TLD) parsing and custom CSP string processing capabilities. The library facilitates managing both `Content-Security-Policy` and `Reporting-Endpoints` headers, making it easier to implement robust web security measures against attacks like XSS. It requires Node.js version 18 or higher.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic Express server and applies a Content-Security-Policy using `express-csp-header`. It demonstrates the use of common directives like `default-src`, `script-src` with `NONCE` for inline scripts, `style-src` with `INLINE`, and `img-src`. It also shows how to enable `report-uri` for violation reporting and access the dynamically generated nonce from `req.nonce`.

import express from 'express';
import { expressCspHeader, INLINE, NONE, SELF, NONCE } from 'express-csp-header';

const app = express();
const port = process.env.PORT || 3000;

app.use(expressCspHeader({
    directives: {
        'default-src': [SELF, 'somehost.com'],
        'script-src': [SELF, INLINE, NONCE],
        'style-src': [SELF, 'mystyles.net', INLINE],
        'img-src': ['data:', 'images.com'],
        'worker-src': [NONE],
        'block-all-mixed-content': true,
        'report-uri': ['https://example.com/csp-report-endpoint']
    },
    reportOnly: false // Set to true to test CSP without blocking resources
}));

app.get('/', (req, res) => {
    // The generated nonce is available on req.nonce if NONCE is used in directives
    const scriptNonce = req.nonce || '';
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>CSP Example</title>
            <style nonce="${scriptNonce}">body { font-family: sans-serif; }</style>
        </head>
        <body>
            <h1>Hello, CSP!</h1>
            <p>This page demonstrates CSP with nonce.</p>
            <script nonce="${scriptNonce}">
                console.log('Script executed with nonce:', '${scriptNonce}');
                // An intentionally blocked inline script without nonce (will appear in console if not allowed by CSP)
                // setTimeout(() => alert('This might be blocked!'), 100);
            </script>
            <img src="https://images.com/example.jpg" alt="Example Image">
        </body>
        </html>
    `);
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
    console.log('Check browser developer tools for CSP header and potential violations.');
});

view raw JSON →