Skip to content

helmet.js custom options for one middleware while enabling others

I want to set some custom options for one of the helmet.js middlewares but I don’t understand if by doing so the other middlewares are enabled or I have to enable them explicitly ?

From helmet.js docs:

// Sets all of the defaults, but overrides `script-src` and disables the default `style-src`
app.use(
  helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
      "script-src": ["'self'", "example.com"],
      "style-src": null,
    },
  })
);

Should I add app.use(helmet()) before the above code ?

Answer

app.use(helmet()) includes all of Helmet’s default middlewares with their default options.

app.use(helmet.contentSecurityPolicy()) only includes the Content Security Policy middleware. In other words, you won’t get the rest of Helmet’s middlewares.

To include all of Helmet’s defaults and customize the CSP middleware, specify it under the top-level helmet():

app.use(
  helmet({
    contentSecurityPolicy: {
      // ...
    },
  })
);