0
0
NestJSframework~5 mins

CORS configuration in NestJS

Choose your learning style9 modes available
Introduction

CORS helps your NestJS app control who can access its resources from other websites. It keeps your app safe by blocking unwanted requests.

When your frontend app runs on a different domain than your NestJS backend.
When you want to allow only specific websites to use your API.
When you want to enable your API to be accessed by mobile apps or other services.
When you want to prevent unauthorized websites from calling your backend.
Syntax
NestJS
const app = await NestFactory.create(AppModule);
app.enableCors({
  origin: 'http://example.com',
  methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
  credentials: true,
});
await app.listen(3000);

The origin option controls which website URLs can access your backend.

Use credentials: true if you want to allow cookies or authorization headers.

Examples
Enable CORS with default settings (allows all origins).
NestJS
app.enableCors();
Allow only requests from https://myfrontend.com.
NestJS
app.enableCors({ origin: 'https://myfrontend.com' });
Allow multiple specific websites to access your API.
NestJS
app.enableCors({ origin: ['https://site1.com', 'https://site2.com'] });
Allow all origins but only GET and POST methods with specific headers.
NestJS
app.enableCors({
  origin: '*',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization']
});
Sample Program

This NestJS app allows CORS requests only from http://localhost:4200 with GET and POST methods. It also allows credentials like cookies.

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: 'http://localhost:4200',
    methods: ['GET', 'POST'],
    credentials: true,
  });
  await app.listen(3000);
  console.log('Server running on http://localhost:3000');
}

bootstrap();
OutputSuccess
Important Notes

Be careful with origin: '*' when using credentials; browsers block this combination.

You can also configure CORS globally in the main.ts file or per route using decorators.

Use browser DevTools Network tab to check CORS headers and errors when testing.

Summary

CORS controls which websites can access your NestJS backend.

Use app.enableCors() to set CORS options simply.

Always specify allowed origins and methods to keep your app secure.