0
0
NestJSframework~5 mins

Compression and security headers in NestJS

Choose your learning style9 modes available
Introduction

Compression makes your app faster by shrinking data sent to users. Security headers protect your app from common web attacks.

When you want your NestJS app to load faster by sending smaller files.
When you want to stop hackers from doing bad things like stealing data or running harmful scripts.
When you want to improve your website's safety and user trust.
When you want to follow best practices for web app performance and security.
When you want to control how browsers handle your app's content.
Syntax
NestJS
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as compression from 'compression';
import * as helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Enable compression middleware
  app.use(compression());

  // Enable security headers middleware
  app.use(helmet());

  await app.listen(3000);
}
bootstrap();

Use compression() to reduce response size and speed up loading.

Use helmet() to add many security headers easily.

Examples
This adds gzip compression to all responses, making data smaller.
NestJS
app.use(compression());
This adds default security headers like Content-Security-Policy and X-Frame-Options.
NestJS
app.use(helmet());
This customizes the Content Security Policy header to allow scripts only from your site and trusted.com.
NestJS
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", 'trusted.com'],
  },
}));
Sample Program

This simple NestJS app uses compression to speed up responses and helmet to add security headers. When you visit http://localhost:3000, it returns a JSON message with compression and security headers applied.

NestJS
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get } from '@nestjs/common';
import * as compression from 'compression';
import * as helmet from 'helmet';

@Controller()
class AppController {
  @Get()
  getHello() {
    return { message: 'Hello, world!' };
  }
}

@Module({
  controllers: [AppController],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Enable compression
  app.use(compression());

  // Enable security headers
  app.use(helmet());

  await app.listen(3000);
  console.log('App running on http://localhost:3000');
}
bootstrap();
OutputSuccess
Important Notes

Compression works best for text data like JSON, HTML, and CSS.

Helmet sets many headers by default, but you can customize or disable parts if needed.

Test your app in browser DevTools Network tab to see compressed responses and security headers.

Summary

Compression makes your app faster by shrinking data sent to users.

Security headers protect your app from common web attacks.

In NestJS, use compression and helmet middleware to add these features easily.