Skip to content

Commit 4e9fc3a

Browse files
committed
docs(security/helmet): add how to use helmet with fastify
1 parent 8b76778 commit 4e9fc3a

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

content/techniques/security.md

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ In this chapter we cover various techniques that help you to increase the securi
66

77
[Helmet](https://github.com/helmetjs/helmet) can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately. Generally, Helmet is just a collection of 14 smaller middleware functions that set security-related HTTP headers (read [more](https://github.com/helmetjs/helmet#how-it-works)).
88

9-
Start by installing the required package:
9+
Start by installing the required package. If you are using [Express](https://expressjs.com/) (default in Nest):
1010

1111
```bash
1212
$ npm i --save helmet
@@ -20,7 +20,23 @@ import * as helmet from 'helmet';
2020
app.use(helmet());
2121
```
2222

23-
> info **Hint** Note that `app.use(helmet())` must come before other calls to `app.use()` or setup functions that may call `app.use()`). This is due to the way the underlying platform (e.g., Express) works, where the order that middleware/routes are defined matters. If you use middleware like `helmet` or `cors` after you define a route, then that middleware will not apply to that route, it will only apply to middleware defined after the route.
23+
If you are using the `FastifyAdapter`, you'll need [fastify-helmet](https://github.com/fastify/fastify-helmet) instead:
24+
25+
```bash
26+
$ npm i --save fastify-helmet
27+
```
28+
29+
[fastify-helmet](https://github.com/fastify/fastify-helmet) should not be used as a middleware, but as a [Fastify plugin](https://www.fastify.io/docs/latest/Plugins/), i.e., by using `app.register()`:
30+
31+
```typescript
32+
import * as helmet from 'fastify-helmet';
33+
// somewhere in your initialization file
34+
app.register(helmet);
35+
// or the following, but note that it's not type safe
36+
// app.getHttpAdapter().register(helmet);
37+
```
38+
39+
> info **Hint** Note that applying `helmet` as global or registering it must come before other calls to `app.use()` or setup functions that may call `app.use()`). This is due to the way the underlying platform (i.e., Express or Fastify) works, where the order that middleware/routes are defined matters. If you use middleware like `helmet` or `cors` after you define a route, then that middleware will not apply to that route, it will only apply to middleware defined after the route.
2440
2541
#### CORS
2642

0 commit comments

Comments
 (0)