How to get rid of CORS errors

I keep getting cors error when I tried to connect my front and back end applications. It works on localhost but when I deployed both of them, it just fails. I did some googling and they said I should add this to my app.js
const corsConfig = {
origin: [
"https://blog-hed03m1mq-complexlity.vercel.app",
"http://localhost:3000",
"https://blog-cms-git-cors-complexlity.vercel.app"
],
credentials: true,
methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
allowedHeaders: ["Content-Type"],
};

app.use(cors(corsConfig));
const corsConfig = {
origin: [
"https://blog-hed03m1mq-complexlity.vercel.app",
"http://localhost:3000",
"https://blog-cms-git-cors-complexlity.vercel.app"
],
credentials: true,
methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
allowedHeaders: ["Content-Type"],
};

app.use(cors(corsConfig));
Which I did but it still doesn't work Frontend - Nextjs, deploy - vercel Backend - Nodejs/express deploy - railway Frontend code executing the function
const response = await fetch(url, {
method: "POST",
headers: {
...headers,
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(values)
const response = await fetch(url, {
method: "POST",
headers: {
...headers,
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(values)
5 Replies
Complexlity
Complexlity•17mo ago
Update: I tried to use render to host the api and till the same thing. I noticed it does not even show the request on the node logs. I pinged /api/v1/sessions (IMAGE 1) but it still doesn't show on the logs (IMAGE 2) could it be the browser?
JulieCezar
JulieCezar•17mo ago
try setting origin: "*" with a * to allow all origins... just to see if it works
Complexlity
Complexlity•17mo ago
Okay 👌 . Will do I just remember I tried that. It didn’t work because I have credentials:true. Apparently, to send credentials, you have to put some allowed domains and cannot used *
wlvz
wlvz•17mo ago
you can change your middleware so that if you hit the api endpoint it will append the headers
export async function middleware(request: NextRequest) {
const response = NextResponse.next()

if (request.nextUrl.pathname.startsWith("/api")) {
response.headers.append("Access-Control-Allow-Origin", "*")
}
//...
return response
}
export async function middleware(request: NextRequest) {
const response = NextResponse.next()

if (request.nextUrl.pathname.startsWith("/api")) {
response.headers.append("Access-Control-Allow-Origin", "*")
}
//...
return response
}
Complexlity
Complexlity•17mo ago
Oh wow. Does that work if you use a different backend server. I use node/express in this case and not the nextjs api route
Want results from more Discord servers?
Add your server