[▲ Vercel Community](/) · [Categories](/categories) · [Latest](/latest) · [Top](/top) · [Live](/live)

[Help](/c/help/9)

# Getting Cors Error in nestJs app

536 views · 0 likes · 2 posts


Alpha Ai12 (@alpha-ai12) · 2024-08-23

I am getting cors error although i done with all the configuration in vercel.json file and handle in my main.ts file as well,
here is my code for vercel.json file
```
{
  "version": 2,
  "builds": [
    {
      "src": "dist/main.js",
      "use": "@vercel/node"
    }
  ],
  
  "headers": [
  {
    "source": "/(.*)",
    "headers": [
      { "key": "Access-Control-Allow-Credentials", "value": "true" },
      { "key": "Access-Control-Allow-Origin", "value": "*" },
      { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
      { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
    ]
  }
],
"rewrites": [
  {
    "source": "/(.*)",
    "destination": "/dist/main.js"
  }
]
}

```
and here is my nestJS  main.ts file
```
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as compression from 'compression';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: '*',
    methods: '*',
    allowedHeaders: '*',
    preflightContinue: false,
    optionsSuccessStatus: 204,
  });
  app.use(
    compression({
      filter: () => {
        return true;
      },
      threshold: 0,
  }));
  await app.listen(3004);
}
bootstrap();

```


Pauline P. Narvas (@pawlean) · 2024-08-23

Hi, @alpha-ai12!

CORS errors are tricky, but let me try and help you out here. :smile: 

Your `vercel.json` configuration is actually correct for setting CORS headers. The CORS configuration in your NestJS `main.ts` file is also correct and should work. 

However, there might be an interaction between Vercel's configuration and NestJS's configuration that's causing issues. Make sure:

- That your NestJS app is properly built and the entry point is correct
- Specific routes in your NestJS application might be overriding the global CORS settings.
- Your frontend might be making requests to the wrong URL

To further debug:

- Check your browser's console for the specific CORS error message.
- Verify that your NestJS application is being served correctly on Vercel by accessing a simple route.
- Ensure that your frontend is making requests to the correct Vercel deployment URL.

Below are some potentially helpful resources to navigate CORS:
* https://www.reddit.com/r/reactjs/comments/sxztdp/nestjs_vercel_cors_no_accesscontrolalloworigin/
* https://vercel.com/templates/next.js/edge-functions-cors
* https://vercel.com/guides/how-to-enable-cors

Let us know how you get on!