|
| 1 | +--- |
| 2 | +title: "How should I use Helmet with non-document responses?" |
| 3 | +--- |
| 4 | + |
| 5 | +Helmet is designed to be easy to use. It sets its security headers for all responses. |
| 6 | + |
| 7 | +Unfortunately, this can lead to unnecessarily headers being set for some responses, hampering performance slightly. For example, you don't need to set the `Content-Security-Policy` header when responding with a PNG image, but you probably _do_ want to set the `Strict-Transport-Security` header. |
| 8 | + |
| 9 | +Here is a list of Helmet headers that are *usually safe to omit unless you're responding with HTML*: |
| 10 | + |
| 11 | +- `Content-Security-Policy` |
| 12 | +- `Cross-Origin-Embedder-Policy` |
| 13 | +- `Cross-Origin-Opener-Policy` |
| 14 | +- `Origin-Agent-Cluster` |
| 15 | +- `Referrer-Policy` |
| 16 | +- `X-DNS-Prefetch-Control` |
| 17 | +- `X-XSS-Protection` |
| 18 | + |
| 19 | +This all depends on your application, though. **If you're not sure, keep the header.** |
| 20 | + |
| 21 | +There are a wide variety of options to address this issue and they are heavily dependent on your application, so it's hard to give a code snippet. But here's a very naïve one: |
| 22 | + |
| 23 | +```javascript |
| 24 | +const helmetForDocuments = helmet(); |
| 25 | +const helmetForNonDocuments = helmet({ |
| 26 | + contentSecurityPolicy: false, |
| 27 | + crossOriginEmbedderPolicy: false, |
| 28 | + crossOriginOpenerPolicy: false, |
| 29 | + originAgentCluster: false, |
| 30 | + referrerPolicy: false, |
| 31 | + xDnsPrefetchControl: false, |
| 32 | + xXssProtection: false, |
| 33 | +}); |
| 34 | + |
| 35 | +// ... |
| 36 | + |
| 37 | +app.get( |
| 38 | + "/my/route", |
| 39 | + (req, res, next) => { |
| 40 | + if (shouldRespondWithDocument(req)) { |
| 41 | + helmetForDocuments(req, res, next); |
| 42 | + } else { |
| 43 | + helmetForNonDocuments(req, res, next); |
| 44 | + } |
| 45 | + }, |
| 46 | + (req, res) => { |
| 47 | + // ... |
| 48 | + }, |
| 49 | +); |
| 50 | +``` |
0 commit comments