This content originally appeared on CSS-Tricks and was authored by Chris Coyier
Whatever, I just needed a title. Everyone’s favorite web security feature has crossed my desk a bunch of times lately and I always feel like that is a sign I should write something because that’s what blogging is.
The main problem with CORS is that developers don’t understand CORS. The basic concept of it is supposed to be easy: don’t run code across origins. Meaning if I, at css-tricks.com
, try to fetch
some JavaScript from an external URL, like any-other-website.com
, the browser will just stop it by default. You’ll see an error in the console. Not allowed.
Unless, that is, the other website sends a header that specifically allows this. My domain can be whitelisted or there could be a wildcard that allows it. There is way more detail here (like preflighting and credentials) and, as ever, the MDN article does a good job on that front.
What have traditionally been hair-pulling moments for me are when CORS seems to behave inconsistently. Two requests will go through and a third will fail, which seems inexplicable, but was reproducible. (Perhaps there was a load balancer involved with half-cached headers? Who knows.) Or I’m trying to use a proxy and the proxy stops working. I can’t even remember all the examples, but I bet I’ve been in meetings trying to debug CORS issues over 100 times in my life.
Anyway, those times where CORS have crossed my desk recently:
- This video, Learn CORS In 6 Minutes, has 10,000 likes and seems to have struck a chord with folks. A non-ironic
npm install cors
was the solution here. - You have to literally tell servers to have the correct headers. So, similar to the video above, I had to do that in a video about Cloudflare Workers, where I used cross-origin (but you don’t have to, which is actually a very cool feature of Cloudflare Workers).
- Jake’s article “How to win at CORS” which includes a playground.
- There are browser extensions (like ones for Firefox and Chrome) that yank in CORS headers for you, which feels like a questionable workaround, but I wouldn’t blame anybody for using in development.
The post Don’t Snore on CORS appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.
This content originally appeared on CSS-Tricks and was authored by Chris Coyier
Chris Coyier | Sciencx (2021-11-10T22:38:05+00:00) Don’t Snore on CORS. Retrieved from https://www.scien.cx/2021/11/10/dont-snore-on-cors/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.