'How to enable and disable upgradeInsecureRequests csp directive using Helmet 4.4.1 version node.js module

I have tried this using Helmet 4.4.1 version both of them below sets to true for upgrade-insecure-requests CSP

upgradeInsecureRequests: [] and upgradeInsecureRequests: ['true']

Which of the above format is correct to use?



Solution 1:[1]

This works for me:

app.use(
        helmet.contentSecurityPolicy({
            directives: {
                "script-src": ["'self'"],
                upgradeInsecureRequests: null
            },
        })
    );

Setting upgradeInsecureRequests to null:

upgradeInsecureRequests: null

Solution 2:[2]

Solved: we can simply add upgradeInsecureRequests: []

Solution 3:[3]

This worked for me:

defaultDirectives = helmet.contentSecurityPolicy.getDefaultDirectives();
delete defaultDirectives['upgrade-insecure-requests'];

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

The delete part removes the upgrade-insecure-requests key in the defaultDirectives object.

Solution 4:[4]

After few hours of trial and errors, I've got it working. I did it like this:

const defaultCspOptions = helmet.contentSecurityPolicy.getDefaultDirectives();
delete defaultCspOptions["upgrade-insecure-requests"]

app.use(helmet({
  contentSecurityPolicy: {
    useDefaults: false,
    directives: { ...defaultCspOptions },
  })
)

Almost like Nico Serrano's answer, yes. In fact it inspired this. I just add useDefaults: false. Otherwise, even though the 'upgrade-insecure-requests' property is no longer exists in the defaultCspOptions, the helmet automatically reappend any missing property with the default value. Rendering the delete part useless.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oscar Escamilla
Solution 2 hitendra
Solution 3 Nico Serrano
Solution 4 yaputra jordi