{"id":17435,"library":"express-csp-header","title":"Content Security Policy Middleware for Express","description":"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.","status":"active","version":"6.3.1","language":"javascript","source_language":"en","source_url":"https://github.com/frux/csp","tags":["javascript","csp","content-security-policy","express","typescript"],"install":[{"cmd":"npm install express-csp-header","lang":"bash","label":"npm"},{"cmd":"yarn add express-csp-header","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-csp-header","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency as it's an Express middleware.","package":"express","optional":false},{"reason":"Used internally for Top-Level Domain (TLD) parsing in the auto-TLD feature.","package":"psl","optional":false}],"imports":[{"note":"The primary middleware function. While CommonJS `require` with destructuring is shown in older examples and still compatible, ESM `import` is preferred for modern Node.js environments. The package ships TypeScript types.","wrong":"const expressCspHeader = require('express-csp-header'); // Incorrect for named export access\nconst { expressCspHeader } = require('express-csp-header'); // Correct CJS, but prefer ESM","symbol":"expressCspHeader","correct":"import { expressCspHeader } from 'express-csp-header';"},{"note":"One of several constants (`INLINE`, `NONE`, `NONCE`, `TLD`) provided for convenience when defining CSP directives. Always import these named exports.","wrong":"const SELF = 'self'; // Hardcoding constant value; less maintainable","symbol":"SELF","correct":"import { SELF } from 'express-csp-header';"},{"note":"Used to dynamically generate a cryptographically secure nonce for `script-src` or `style-src` directives. The generated nonce is accessible via `req.nonce`.","wrong":"import { Nonce } from 'express-csp-header';","symbol":"NONCE","correct":"import { expressCspHeader, NONCE } from 'express-csp-header';"}],"quickstart":{"code":"import express from 'express';\nimport { expressCspHeader, INLINE, NONE, SELF, NONCE } from 'express-csp-header';\n\nconst app = express();\nconst port = process.env.PORT || 3000;\n\napp.use(expressCspHeader({\n    directives: {\n        'default-src': [SELF, 'somehost.com'],\n        'script-src': [SELF, INLINE, NONCE],\n        'style-src': [SELF, 'mystyles.net', INLINE],\n        'img-src': ['data:', 'images.com'],\n        'worker-src': [NONE],\n        'block-all-mixed-content': true,\n        'report-uri': ['https://example.com/csp-report-endpoint']\n    },\n    reportOnly: false // Set to true to test CSP without blocking resources\n}));\n\napp.get('/', (req, res) => {\n    // The generated nonce is available on req.nonce if NONCE is used in directives\n    const scriptNonce = req.nonce || '';\n    res.send(`\n        <!DOCTYPE html>\n        <html>\n        <head>\n            <title>CSP Example</title>\n            <style nonce=\"${scriptNonce}\">body { font-family: sans-serif; }</style>\n        </head>\n        <body>\n            <h1>Hello, CSP!</h1>\n            <p>This page demonstrates CSP with nonce.</p>\n            <script nonce=\"${scriptNonce}\">\n                console.log('Script executed with nonce:', '${scriptNonce}');\n                // An intentionally blocked inline script without nonce (will appear in console if not allowed by CSP)\n                // setTimeout(() => alert('This might be blocked!'), 100);\n            </script>\n            <img src=\"https://images.com/example.jpg\" alt=\"Example Image\">\n        </body>\n        </html>\n    `);\n});\n\napp.listen(port, () => {\n    console.log(`Server running at http://localhost:${port}`);\n    console.log('Check browser developer tools for CSP header and potential violations.');\n});","lang":"typescript","description":"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`."},"warnings":[{"fix":"Manually review and adjust your CSP directives if you were depending on implicit removal of `'none'` when other sources were present for the same directive. Ensure each directive explicitly states its allowed sources without relying on removed values.","message":"Version 6.0.0 introduced a breaking change where the `\"'none'\"` value is no longer implicitly removed for merged directives that have multiple declarations. This can alter the final CSP string if you rely on such merging behavior.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Ensure your project is running on Node.js version 18 or higher. Update your Node.js environment or adjust your project's `engines` field accordingly.","message":"Version 5.0.0 increased the minimum supported Node.js version to 10. The current package version (6.x) requires Node.js `>=18`. Using this package with older Node.js versions will result in runtime errors.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Migrate your CSP configurations from using the `extend` option to the `presets` option. Refer to the `csp-header` documentation for the correct `presets` usage.","message":"Version 5.0.0 deprecated and subsequently removed the `extend` option in favor of `presets`. If you were using `extend` for combining CSP rules, your configuration will no longer work.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Update your import statements to use named destructuring: `const { expressCspHeader } = require('express-csp-header');` for CommonJS or `import { expressCspHeader } from 'express-csp-header';` for ESM.","message":"Version 3.0.0 changed `expressCspHeader` from a default export to a named export. This means `const expressCspHeader = require('express-csp-header')` no longer works and requires destructuring.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Prioritize `report-uri` in conjunction with `Content-Security-Policy-Report-Only` for initial deployment and testing, then transition to enforced `Content-Security-Policy` with a robust `report-uri` or `report-to` configuration as needed for modern browsers. Consult MDN Web Docs for the latest CSP reporting recommendations.","message":"`Reporting-Endpoints` is no longer recommended by modern browsers in favor of `Content-Security-Policy-Report-Only` (using `report-uri`) or a dedicated `Report-To` header. While `express-csp-header` supports `report-to` for `csp-header`, users should be aware of current browser recommendations and policy header best practices.","severity":"gotcha","affected_versions":">=5.0.0"},{"fix":"Always deploy CSP in `reportOnly: true` mode first to collect violation reports and fine-tune your policy. Use the browser's developer console and your configured `report-uri` endpoint to identify and resolve all legitimate resource blocks before enforcing the policy.","message":"Improperly configured Content Security Policy directives can lead to legitimate resources being blocked, resulting in a broken or unusable website. This is especially true for directives like `script-src` and `style-src` if `unsafe-inline` or appropriate nonces/hashes are not used for inline content.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Inspect your browser's developer console for the exact CSP violation message. Adjust the corresponding CSP directive in `express-csp-header` to include the blocked source (e.g., `'unsafe-inline'`, `'unsafe-eval'`, `NONCE`, or specific domains). For inline scripts/styles, use `NONCE` or `INLINE` (with caution).","cause":"A script (or other resource) is attempting to load from an origin or with attributes (e.g., inline) not permitted by the `script-src` (or other relevant) CSP directive.","error":"Refused to load the script '...' because it violates the following Content Security Policy directive: \"script-src 'self'\"."},{"fix":"Ensure `app.use(expressCspHeader(...))` is placed early in your Express middleware chain, typically before any routes or other middleware that might send responses.","cause":"The `express-csp-header` middleware is being applied after a response has already been partially or fully sent by another middleware or route handler.","error":"Cannot set headers after they are sent to the client"},{"fix":"Verify that `NONCE` is included in the relevant `script-src` or `style-src` directives passed to `expressCspHeader`. Also, ensure the middleware is active for the route where `req.nonce` is accessed.","cause":"You are trying to access `req.nonce` but either `NONCE` was not included in your `script-src` or `style-src` directives, or the middleware was not correctly applied before the route handler.","error":"TypeError: Cannot read properties of undefined (reading 'nonce')"}],"ecosystem":"npm","meta_description":null}