Skip to content

Commit 893e1b1

Browse files
Merge pull request #1125 from iansltx/fastify-compress
Add more detail to Fastify compression instructions
2 parents d514396 + 13ad9ce commit 893e1b1

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

content/techniques/compression.md

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
### Compression
22

3-
Compression can greatly decrease the size of the response body, thereby increasing the speed of a web app. Use the [compression](https://github.com/expressjs/compression) middleware package to enable gzip compression.
3+
Compression can greatly decrease the size of the response body, thereby increasing the speed of a web app.
44

5-
#### Installation
5+
For **high-traffic** websites in production, it is strongly recommended to offload compression from the application server - typically in a reverse proxy (e.g., Nginx). In that case, you should not use compression middleware.
6+
7+
#### Use with Express (default)
8+
9+
Use the [compression](https://github.com/expressjs/compression) middleware package to enable gzip compression.
610

711
First install the required package:
812

@@ -18,6 +22,28 @@ import * as compression from 'compression';
1822
app.use(compression());
1923
```
2024

21-
> info **Hint** If using the `FastifyAdapter`, consider using [fastify-compress](https://github.com/fastify/fastify-compress) instead.
25+
#### Use with Fastify
2226

23-
For **high-traffic** websites in production, it is strongly recommended to offload compression from the application server - typically in a reverse proxy (e.g., Nginx). In that case, you should not use compression middleware.
27+
If using the `FastifyAdapter`, you'll want to use [fastify-compress](https://github.com/fastify/fastify-compress):
28+
29+
```bash
30+
$ npm i --save fastify-compress
31+
```
32+
33+
Once the installation is complete, apply the fastify-compress middleware as global middleware.
34+
35+
```typescript
36+
import * as compression from 'fastify-compress';
37+
// somewhere in your initialization file
38+
app.register(compression);
39+
```
40+
41+
By default, fastify-compress will use Brotli compression (on Node >= 11.7.0) when browsers indicate support for the encoding. While Brotli is quite efficient in terms of compression ratio, it's also quite slow. Due to this, you may want to tell fastify-compress to only use deflate and gzip to compress responses; you'll end up with larger responses but they'll be delivered much more quickly.
42+
43+
To specify encodings, provide a second argument to `app.register`:
44+
45+
```typescript
46+
app.register(compression, { encodings: ['gzip', 'deflate'] });
47+
```
48+
49+
The above tells `fastify-compress` to only use gzip and deflate encodings, preferring gzip if the client supports both.

0 commit comments

Comments
 (0)