DEV Community

How to handle CORS issues when deploying a nodeJS express app on vercel??

Kartikey Jaiswal on January 23, 2024

When we deploy a simple nodejs express app to vercel, we are most likely to encounter cors issues most of the times. Personally, I often get cors e...
Collapse
 
ravavyr profile image
Ravavyr

I'll say this "works" only because you're saying "*" which means "any domain can send me requests"
That makes this is a "bad" or "not secure" setup.
Unless you want any website on the planet to hit your api directly.

To properly setup CORS on express you should be defining which domains are allowed to send requests to your server. In your case that means replacing that * with
"virmigo.vercel.app" so only that domain can send requests to your backend.
Of course if you're running a local copy or have other subdomains you're using, you need to add those as well comma-separated or they'll get CORS errors.

You should also restrict the METHODS you actually need. Chances are you're only using GET, POST, and OPTIONS [is necessary for CORS verification by the browser]
You might be using PUT if someone taught you to, but PATCH and DELETE almost no one uses. Ideally we'd all just freaking use POST all the time and just get on with our lives, but some disagree and pretend the server cares about what we want, it really doesn't.

I hope this helps you and anyone else who came across this to understand CORS a bit better.

Collapse
 
mwazowsky profile image
Saifulloh Fadli

And also make sure you use two version of your vercel url in your backend cors access, for example in nest js main.ts file

app.enableCors({
origin: [
'http://localhost:5173',
'https://www.yourdomain.com',
'https://yourdomain.com',
],
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
});

Collapse
 
adeelsadique profile image
AdeelSadique

it's not working

Collapse
 
muhammadbilalellahi profile image
Muhammad Bilal Ellahi

This worked but now it gives gateway timeout error.

Collapse
 
muhammadbilalellahi profile image
Muhammad Bilal Ellahi

Checked the error. it is due to vercel limit to request for hobby plan which is 10 seconds. This happens when you request from example: mongodb from your server which takes time. Thus, either buy pro plan or dont use/request other api.

It works fine with resend or nodemailer and such. Vercel allows that for free tier.

Collapse
 
sadiqur_rahman_b21601c42f profile image
Sadiqur Rahman

do not use this solution. it causes server crash

Collapse
 
matiasenrique profile image
MatiasEnrique

this does not work

Collapse
 
saif_hamdare profile image
Saif Hamdare

short and easy solution worked for me just created. vercel.json in route pasted the provided json code. its work like buter

Collapse
 
lcse1706 profile image
Lukas Czarniecki

For me it's working, thanks. I was struggling with it from 2 days.