Skip to content

Commit 627492b

Browse files
committed
FAQ: "How should I use Helmet with non-document responses?"
1 parent 9f0575e commit 627492b

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

content/faq/_index.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@ title: "Frequently asked questions (FAQ)"
1010
- [How do I upgrade from Helmet 3 to Helmet 4?]({{< ref "faq/helmet-4-upgrade" >}})
1111
- [How do I set a Content Security Policy nonce?]({{< ref "faq/csp-nonce-example" >}})
1212
- [How do I set both `Content-Security-Policy` and `Content-Security-Policy-Report-Only` headers?](https://github.com/helmetjs/helmet/issues/351#issuecomment-1015498560)
13+
- [How should I use Helmet with non-document responses?]({{< ref "faq/non-documents" >}})
1314
- [Who made Helmet?]({{< ref "faq/contributors" >}})

content/faq/non-documents.md

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)