NestJS Compression
In NestJS, compressing responses can significantly reduce the amount of data transmitted over the network, thereby improving user experience. NestJS integrates seamlessly with the Fastify framework, which provides a plugin called @fastify/compress to handle HTTP response compression.
Installing Dependencies
First, install the @fastify/compress plugin.
npm install @fastify/compressEnabling Compression
Next, register the @fastify/compress plugin in your NestJS application.
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import compression from '@fastify/compress';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
// Register the compression plugin
await app.register(compression);
await app.listen(3000);
}
bootstrap();Configuring Compression
You can configure the behavior of the compression plugin by passing options.
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import compression from '@fastify/compress';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
// Configure the compression plugin
await app.register(compression, {
// Optional configuration
// For example, set the compression level
// level: 6, // 0-9, 0 means no compression, 9 means maximum compression
});
await app.listen(3000);
}
bootstrap();Verifying Compression
To confirm that compression is working, you can use browser developer tools or the curl command to check if the response headers include the Content-Encoding field, indicating that the response is compressed.
curl -I http://localhost:3000/some-endpointIf everything is set up correctly, you should see response headers like this:
HTTP/1.1 200 OK
Date: Thu, 08 Aug 2024 12:00:00 GMT
Content-Type: application/json
Content-Length: 1234
Content-Encoding: gzip
...Customizing Compression Behavior
You can control which routes should be compressed by using custom middleware.
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import compression from '@fastify/compress';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
// Register the compression plugin with custom middleware
await app.register(compression, {
// Custom middleware
middleware: async (request, reply) => {
// For example, check the request path
if (request.url === '/no-compress') {
// Skip compression for specific paths
return false;
}
return true;
},
});
await app.listen(3000);
}
bootstrap();



