0

This is not only a question, also an answer to my problem which took me a lot to resolve, I believe some devs will find it useful.

Let's start with some basic info:

  • The client app is using NextJs.
  • The server app is using NestJs deployed using the Vercel service.

Everything works fine in localhost, but when deployed the requests are always blocked by the CORS.

The server app deployment config (vercel.json) is the following:

{
  "version": 2,
  "builds": [
    {
      "src": "src/main.ts",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "src/main.ts",
      "methods": [
        "GET",
        "POST",
        "PUT",
        "PATCH",
        "DELETE"
      ]
    }
  ]
}

In the server app, I enabled the CORS in the main.ts file:

app.enableCors({
    allowedHeaders: '*',
    origin: '*',
    credentials: true,
  });

Using any client I used (NextJs, Angular and even Insomnia and Postman) it shows that the CORS are set to accept any origin, still it's still blocking the requests.

2 Answers 2

1

The answer is not related to NextJs or NestJs but only to the vercel deployment config which needs to accept the OPTIONS type of HTTP request, the correct vercel.json file should look like this:

{
  "version": 2,
  "builds": [
    {
      "src": "src/main.ts",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "src/main.ts",
      "methods": [
        "GET",
        "POST",
        "PUT",
        "PATCH",
        "OPTIONS",
        "DELETE"
      ]
    }
  ]
}

Unfortunately, I didn't find this info in any docs I looked in, it only came up since HTTP requests of type OPTIONS are being used in the CORS mechanism.

Sign up to request clarification or add additional context in comments.

Comments

0

Besides applying the CORS config for vercel, described here, you will also need your vercel lambda function to return a 200 status code for request using the OPTIONS method.

Please also that your vercel config needs to allow any custom header that you may be using when querying the endpoint. Lets say your GET request includes a header X-UserSession, such header should be allowed by CORS config as:

{ "key": "Access-Control-Allow-Headers", "value": "X-UserSession" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.