Compression makes your app faster by shrinking data sent to users. Security headers protect your app from common web attacks.
Compression and security headers in 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.
app.use(compression());
app.use(helmet());
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'trusted.com'],
},
}));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.
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();
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.
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.