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.