0
0
NestJSframework~5 mins

Third-party middleware (cors, helmet) in NestJS

Choose your learning style9 modes available
Introduction

Third-party middleware like cors and helmet help protect your NestJS app and make it work well with other websites.

When you want to allow your API to be accessed from other websites safely (use CORS).
When you want to add security headers to protect your app from common web attacks (use Helmet).
When you build a public API that many clients will use from different domains.
When you want to quickly add security best practices without writing complex code.
When you want to control who can access your backend resources.
Syntax
NestJS
import * as cors from 'cors';
import * as helmet from 'helmet';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

  app.use(cors());
  app.use(helmet());

  await app.listen(3000);
}

Use app.use() to add middleware in NestJS.

Both cors() and helmet() are functions that return middleware.

Examples
This enables default CORS settings, allowing all origins.
NestJS
app.use(cors());
This restricts access to only https://example.com.
NestJS
app.use(cors({ origin: 'https://example.com' }));
This adds many security headers automatically.
NestJS
app.use(helmet());
This sets a strict content security policy to allow resources only from your own site.
NestJS
app.use(helmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"] } }));
Sample Program

This NestJS app uses cors middleware to allow cross-origin requests and helmet middleware to add security headers. When you run it, the server listens on port 3000.

NestJS
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cors from 'cors';
import * as helmet from 'helmet';

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

  // Enable CORS for all origins
  app.use(cors());

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

  await app.listen(3000);
  console.log('Server running on http://localhost:3000');
}

bootstrap();
OutputSuccess
Important Notes

Always configure CORS carefully to avoid exposing your API to unwanted sites.

Helmet sets many headers by default, but you can customize it for your needs.

Use browser DevTools Network tab to check CORS headers and security headers in responses.

Summary

CORS middleware controls which websites can access your API.

Helmet middleware adds security headers to protect your app.

Use app.use() in NestJS to add these middlewares easily.