{"id":16830,"library":"helmet","title":"Helmet","description":"Helmet is a popular middleware package for Express and Connect applications, designed to enhance web security by automatically setting various HTTP response headers. The current stable version is 8.1.0, compatible with Node.js 18 and later. Helmet typically releases major versions at a moderate pace, incorporating updates to security best practices and deprecating outdated headers. Its key differentiator is its ease of use, providing a sensible default set of 12 security headers out-of-the-box, including `Content-Security-Policy`, `Cross-Origin-Opener-Policy`, and `Strict-Transport-Security`. While providing robust defaults, Helmet is highly configurable, allowing developers to fine-tune individual header directives or disable specific headers entirely to suit their application's needs, making it a go-to solution for foundational web security in Node.js environments.","status":"active","version":"8.1.0","language":"javascript","source_language":"en","source_url":"git://github.com/helmetjs/helmet","tags":["javascript","express","security","headers","backend","content-security-policy","cross-origin-embedder-policy","cross-origin-opener-policy","cross-origin-resource-policy","typescript"],"install":[{"cmd":"npm install helmet","lang":"bash","label":"npm"},{"cmd":"yarn add helmet","lang":"bash","label":"yarn"},{"cmd":"pnpm add helmet","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Helmet v6+ is primarily designed for ESM. While `require` might work in some CJS contexts, the recommended and type-safe approach for Node.js >=18 is ESM `import`.","wrong":"const helmet = require('helmet');","symbol":"helmet","correct":"import helmet from 'helmet';"},{"note":"Import types for configuration options, especially when using TypeScript, to leverage autocompletion and type checking.","symbol":"HelmetOptions","correct":"import type { HelmetOptions } from 'helmet';"},{"note":"Individual header middlewares can be imported for specific use cases or to override global Helmet settings. Use camelCase for named imports.","wrong":"import { x-content-type-options } from 'helmet';","symbol":"SpecificHeaderMiddleware","correct":"import { xContentTypeOptions } from 'helmet';"}],"quickstart":{"code":"import express from 'express';\nimport helmet from 'helmet';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Apply Helmet with default security headers\napp.use(helmet());\n\n// Example: Customize Content Security Policy (CSP)\n// This CSP allows scripts only from 'self' (your domain) and 'cdn.example.com'\n// and disallows inline scripts unless explicitly whitelisted with a nonce.\napp.use(\n  helmet({\n    contentSecurityPolicy: {\n      directives: {\n        defaultSrc: [\"'self'\"],\n        scriptSrc: [\"'self'\", 'cdn.example.com'],\n        styleSrc: [\"'self'\", \"'unsafe-inline'\"], // 'unsafe-inline' often needed for CSS frameworks\n        imgSrc: [\"'self'\", 'data:'],\n        connectSrc: [\"'self'\"],\n        fontSrc: [\"'self'\", 'https:', 'data:'],\n        objectSrc: [\"'none'\"],\n        upgradeInsecureRequests: true,\n      },\n    },\n  }),\n);\n\n// Route to demonstrate the application\napp.get('/', (req, res) => {\n  res.send(`\n    <!DOCTYPE html>\n    <html lang=\"en\">\n    <head>\n        <meta charset=\"UTF-8\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n        <title>Secure App</title>\n    </head>\n    <body>\n        <h1>Hello, secure world with Helmet!</h1>\n        <script src=\"/test-script.js\"></nscript>\n    </body>\n    </html>\n  `);\n});\n\n// Simple static file for script-src testing\napp.get('/test-script.js', (req, res) => {\n  res.set('Content-Type', 'application/javascript');\n  res.send('console.log(\"Script loaded securely!\");');\n});\n\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Open your browser to see security headers in action.');\n});","lang":"typescript","description":"This quickstart demonstrates how to initialize Helmet with default security headers in an Express application and provides an example of custom Content Security Policy (CSP) configuration."},"warnings":[{"fix":"Migrate your project to use ESM `import` statements and configure `package.json` with `\"type\": \"module\"` if necessary. If a CJS-only project, ensure appropriate loaders or bundler configurations are in place to handle ESM dependencies.","message":"Helmet versions 6 and above are primarily ESM (ECMAScript Modules) by default. Projects using CommonJS (`require`) may encounter `ERR_REQUIRE_ESM` or other import issues, especially in modern Node.js environments.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Upgrade your Node.js environment to version 18 or higher.","message":"Node.js versions below 18 are no longer supported since Helmet v8. Attempting to use Helmet v8.x with older Node.js versions will result in runtime errors.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Review your application's security requirements and explicitly enable any previously relied-upon headers if still needed, or use separate, dedicated packages for removed functionalities (e.g., `expect-ct` package for `Expect-CT`). Note that `X-XSS-Protection` is often disabled for security reasons.","message":"Several headers have been removed or disabled by default in recent major versions (e.g., `X-Powered-By` in v4, `X-XSS-Protection` and `Expect-CT` in v6/v7). Refer to the changelog for specific version changes.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Thoroughly test your CSP in a development environment. Start with `reportOnly: true` to log violations without enforcing them. Gradually refine directives, explicitly allowing necessary sources and considering `nonce` attributes or hashes for inline scripts/styles instead of `unsafe-inline` where possible.","message":"Content Security Policy (CSP) is powerful but complex. Misconfigurations can block legitimate resources (scripts, styles, images) and break your application's functionality, especially with inline content or external CDNs.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Place `app.use(helmet());` at the beginning of your middleware stack, before defining routes or other middleware that might send responses.","message":"The order of middleware matters in Express/Connect applications. Helmet should generally be applied early in your middleware chain to ensure all routes and subsequent middlewares receive the security headers.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change your import statement from `const helmet = require('helmet');` to `import helmet from 'helmet';`. Ensure your `package.json` specifies `\"type\": \"module\"` if it's a pure ESM project, or use a bundler that handles ESM correctly.","cause":"Attempting to import Helmet using CommonJS `require()` in an environment or project configured for ES Modules, or when Helmet itself is published as an ESM-only package.","error":"ERR_REQUIRE_ESM: require() of ES Module .../node_modules/helmet/index.js from ... not supported."},{"fix":"Modify your `contentSecurityPolicy` directives in Helmet to include the allowed domain for scripts, e.g., `scriptSrc: [\"'self'\", 'https://cdn.example.com']`. For inline scripts, consider using `nonce` attributes or hashes.","cause":"Your Content Security Policy (CSP) is blocking a script from loading because its source is not explicitly allowed in the `script-src` directive. The default Helmet CSP is strict.","error":"Refused to load the script 'https://cdn.example.com/script.js' because it violates the following Content Security Policy directive: \"script-src 'self'\"."},{"fix":"For ESM, ensure you use `import helmet from 'helmet';`. For CommonJS in older projects, use `const helmet = require('helmet');` and then `app.use(helmet());`.","cause":"This error typically occurs if Helmet is imported incorrectly. It is a default export in its ESM form, or the CommonJS `require` result is not directly callable as a function.","error":"Helmet is not a function"}],"ecosystem":"npm","meta_description":null}