How to use helmet?

4.3k Views Asked by At

I want to use helmet package to do the following:

set X-Frame-Options = SAMEORIGIN

Disable the X-Powered-By header.

What should Content-Security-Policy be and how do I set it using helmet? How about Access-Control-Allow-Origin?

I also want to use it to enable best practices for security. What do you suggest? What are these best practices and how do I set them?

2

There are 2 best solutions below

0
On BEST ANSWER

Maintainer of Helmet here.

First of all, Helmet is not enough to make your Express apps secure. That requires understanding best practices, vulnerabilities, and much more. Helmet only tries to tackle a narrow piece of that puzzle: setting various HTTP response headers related to security.

For example, by default, Helmet will set a header called X-Frame-Options to SAMEORIGIN. This header doesn't magically make your app secure, but it can help mitigate clickjacking attacks. It will also disable a header called X-Powered-By by default, which

Here's how you use Helmet with all of its default settings:

app.use(helmet());

If you want to, say, override the default value for X-Frame-Options, you could do something like this:

// Sets all of the defaults except for X-Frame-Options,
// which is set to "DENY" instead of its default
app.use(helmet({
  frameguard: { action: 'DENY' },
}));

And if you want Helmet to ignore the X-Frame-Options header completely:

// Sets all of the defaults except for X-Frame-Options
app.use(helmet({
  frameguard: false,
}));

By default, Helmet is responsible for 11 headers, including the two mentioned above.

Helmet's most important, and most difficult to configure, header is Content-Security-Policy. It's not worth describing in depth here; I recommend reading MDN's introductory article.

Helmet can help you set the Content-Security-Policy header, which you can read more about on Helmet's docs. Here's a simple example:

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

You also asked about Access-Control-Allow-Origin. This is part of something called Cross-Origin Resource Sharing, which Helmet does not touch.

1
On

You can write something like this:

app.use(helmet({
  frameguard: false // for SAMEORIGIN
}));

app.disable('x-powered-by'); // for disable the X-Powered-By header.