Getting Cors Error in nestJs app

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();

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:

Let us know how you get on!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.