Member-only story
How CORS works in the background — Web Application Security
Data theft, cross-site scripting (XSS), API hijacking, and origin reflection attacks are common threats in the digital world. To combat these risks, developers rely on a powerful mechanism known as CORS (Cross-Origin Resource Sharing).
But what exactly is CORS, how does it prevent these attacks, and what happens behind the scenes? Let’s break it down.
What is CORS?
CORS, or Cross-Origin Resource Sharing, is a security feature implemented by web browsers to control how resources can be requested from a different origin (domain, port, or scheme) than the one the web page is served from.
For example, if a web application hosted on simplified.ninja
tries to fetch data from an API on notion.so
, the browser will block the request unless notion.so
explicitly allows simplified.ninja
through its CORS policy.
How does CORS work?
CORS operates using HTTP headers and a preflight request mechanism to determine whether a server permits a request before the browser proceeds with it.
Preflight Requests
When a script initiates a cross-origin request using fetch()
or XMLHttpRequest
, the browser first sends an OPTIONS request (preflight request) to the…