I am experiencing CORS issues between my NestJS API and NextJS frontend applications.
Setup
-
API: Developed with NestJS, deployed on Vercel. CORS is configured in
main.ts
to allow requests fromhttps://app.sanguedefarrapos.com.br
. The API is accessible athttps://api.sanguedefarrapos.com.br
and works correctly via Postman. -
Frontend: Developed with NextJS, also deployed on Vercel. The frontend communicates with the API using both server-side and client-side components.
Issue
While server-side requests to the API work fine, client-side requests result in a CORS error. Here is an example of a client-side request:
"use client";
import { useEffect, useState } from "react";
import { parseCookies } from "nookies";
export function GroupSelect({ onChange, value }) {
const [groups, setGroups] = useState([]);
useEffect(() => {
(async () => {
const { "nextauth.token": token } = parseCookies();
if (!token) {
return;
}
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/groups`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error(await response.json().message);
}
setGroups(await response.json());
})();
}, []);
// UI rendering logic
}
However, I receive the following error when making this request from the client-side component:
Access to fetch at 'https://api.sanguedefarrapos.com.br/groups' from origin 'https://app.sanguedefarrapos.com.br' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Attempted Solutions
I have also tried enabling CORS with the default configuration in NestJS using app.enableCors(), but this did not resolve the issue either. The problem persists with client-side requests being blocked due to CORS policy.
Additional Context
- API URL:
https://api.sanguedefarrapos.com.br
- Frontend URL:
https://app.sanguedefarrapos.com.br
Given my configuration, I expected the CORS settings to allow requests from https://app.sanguedefarrapos.com.br
. What might be missing or incorrectly configured in my setup?
Any insights or suggestions would be greatly appreciated.