|
| 1 | +--- |
| 2 | +title: "You might not need Helmet" |
| 3 | +--- |
| 4 | + |
| 5 | +Helmet is designed to be easy to use and integrate, but if you want to avoid a dependency and get a slight performance boost, here's how. |
| 6 | + |
| 7 | +By default, Helmet adds 12 HTTP response headers and removes one. |
| 8 | + |
| 9 | +To add Helmet's default response headers, define an object that contains the headers you want to set, then add them in a single middleware. For example: |
| 10 | + |
| 11 | +```js |
| 12 | +const HEADERS = { |
| 13 | + "Content-Security-Policy": |
| 14 | + "default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests", |
| 15 | + "Cross-Origin-Opener-Policy": "same-origin", |
| 16 | + "Cross-Origin-Resource-Policy": "same-origin", |
| 17 | + "Origin-Agent-Cluster": "?1", |
| 18 | + "Referrer-Policy": "no-referrer", |
| 19 | + "Strict-Transport-Security": "max-age=15552000; includeSubDomains", |
| 20 | + "X-Content-Type-Options": "nosniff", |
| 21 | + "X-DNS-Prefetch-Control": "off", |
| 22 | + "X-Download-Options": "noopen", |
| 23 | + "X-Frame-Options": "SAMEORIGIN", |
| 24 | + "X-Permitted-Cross-Domain-Policies": "none", |
| 25 | + "X-XSS-Protection": "0", |
| 26 | +}; |
| 27 | + |
| 28 | +app.use((req, res, next) => { |
| 29 | + res.set(HEADERS); |
| 30 | + next(); |
| 31 | +}); |
| 32 | +``` |
| 33 | + |
| 34 | +Feel free to tweak this object as you wish. It doesn't just have to be for Helmet-related headers; if there's a header you always want to set, you can do so here. |
| 35 | + |
| 36 | +Express sets the `X-Powered-By` header [by default](https://expressjs.com/en/4x/api.html#app.settings.table), which Helmet removes. You can override this Express default like this: |
| 37 | + |
| 38 | +```js |
| 39 | +app.disable("x-powered-by"); |
| 40 | +``` |
| 41 | + |
| 42 | +(This should be done at the top level; no need to do this inside of middleware or anything.) |
| 43 | + |
| 44 | +In my testing, this was about 5%–10% faster than using Helmet, but your performance may vary. |
| 45 | + |
| 46 | +You may still wish to use Helmet as it tries to make things easy to use, but now you can see that you don't have to! |
0 commit comments