How to Fix CORS Error in NestJS: Simple Steps
CORS error in NestJS, enable CORS in your main application file by calling app.enableCors(). This allows your server to accept requests from different origins and prevents the browser from blocking them.Why This Happens
CORS (Cross-Origin Resource Sharing) errors happen when your frontend tries to access a backend server on a different domain or port, but the backend does not allow it. Browsers block these requests for security unless the server explicitly permits them.
In NestJS, if you don't enable CORS, the server won't send the right headers, causing the browser to block the request.
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Missing app.enableCors() here await app.listen(3000); } bootstrap();
The Fix
To fix the CORS error, you need to tell NestJS to allow requests from other origins by enabling CORS. You do this by calling app.enableCors() in your main bootstrap function. You can also configure which origins are allowed.
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', // allow this frontend origin methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'], credentials: true, }); await app.listen(3000); } bootstrap();
Prevention
Always enable CORS in your NestJS app if your frontend and backend run on different origins. Use specific origins instead of '*' to improve security. Test your API with tools like Postman or browser DevTools to confirm CORS headers are set correctly.
Keep your CORS settings updated if your frontend URL changes. Use environment variables to manage allowed origins for different environments (development, production).
Related Errors
Other common errors related to CORS include:
- Preflight request failure: Happens when the OPTIONS request is blocked or not handled properly. Fix by ensuring your server handles OPTIONS requests.
- Credential issues: If you use cookies or authentication, set
credentials: trueinenableCorsand configure frontend fetch requests accordingly.