What is Cross-Origin Resource Sharing (CORS)?

SecurityApple

Cross-Origin Resource Sharing (CORS)

Let me explain CORS (Cross-Origin Resource Sharing) by starting with why it exists and building up to how it works.

Imagine you're visiting a website at bank.com. For security reasons, your web browser follows what's called the "Same-Origin Policy" - it only lets the webpage make requests to the same domain it came from. This means the JavaScript running on bank.com can't naturally make requests to analytics.com or any other domain. This policy exists to protect users from malicious websites trying to access private information on other sites you're logged into.

However, in modern web development, we often need websites to communicate with different domains. For example, a frontend running on frontend.com might need to fetch data from an API at api.com. This is where CORS comes in.

CORS is a security protocol that lets servers tell browsers which other domains are allowed to access their resources. Here's how it works:

When your browser makes a request to a different domain, it first sends what's called a "preflight" request (using the HTTP OPTIONS method) to ask the server for permission.

This preflight request includes headers like:

Origin: https://frontend.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

The server then responds with headers that specify what's allowed:

Access-Control-Allow-Origin: https://frontend.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 3600

These headers tell the browser:

  • Which origins can access the resource (Access-Control-Allow-Origin)
  • Which HTTP methods are permitted (Access-Control-Allow-Methods)
  • Which headers can be included (Access-Control-Allow-Headers)
  • How long the browser should cache these permissions (Access-Control-Max-Age)

Only if the server's response includes the correct permissions will the browser proceed with the actual request.

For simple requests (like basic GET requests without custom headers), the browser might skip the preflight and make the request directly, but the server still needs to respond with the appropriate CORS headers.

A common point of confusion is why we can't just disable this security feature. Without CORS, malicious websites could make requests to any domain using your logged-in credentials, potentially accessing or modifying your private data on other websites.

To implement CORS in practice, you'll typically configure your server to send the appropriate headers. For example, in Express.js, you might use middleware like this:

app.use(
cors({
origin: 'https://frontend.com',
methods: ['GET', 'POST', 'PUT'],
allowedHeaders: ['Content-Type'],
})
);
00:00