Serksa
All Concepts
Security

CORS Explained

1

What is it?

<strong>CORS (Cross-Origin Resource Sharing)</strong> is a security feature that controls which websites can access your API. Browsers block requests from different domains by default; CORS headers tell the browser which cross-origin requests to allow.

2

Think of it like...

The Gated Community Analogy

Your API is like a gated community. By default, the gate (CORS) blocks all visitors from other neighborhoods (domains). You configure CORS to allow specific visitors or everyone.

🏘️

Your API (Community)

Protected resource

🚧

CORS (Gate)

Controls access

🚗

Other Websites (Visitors)

Want to enter

3

Visual Flow

🌐Website A

Makes Request

🛡️Browser

Checks CORS

🖥️API (Website B)

Allows or Blocks

4

Where you see it

1

Browser makes request

example.com tries to call api.other.com

2

Browser checks origin

Sees request is cross-origin (different domain)

3

Preflight request (OPTIONS)

Browser asks: 'Is this allowed?'

4

Server responds with CORS headers

Access-Control-Allow-Origin: example.com

5

Browser allows or blocks

If origin is allowed, request proceeds

5

Common Mistake

Wrong

"CORS is an API security feature"

Correct

CORS is a <strong>browser security feature</strong>. It only affects browser requests. Tools like Postman or curl bypass CORS because they're not browsers.

💡 Real-World Example

Frontend calling backend API:

1

Frontend: https://myapp.com

2

API: https://api.myapp.com (different subdomain = cross-origin)

3

Without CORS: Browser blocks the request

4

With CORS header: Access-Control-Allow-Origin: https://myapp.com → Allowed