Course contentsShow
← Security
Lesson 859 of 3,05218. Web Security - CSRF and Request ForgeryFree lesson

CORS Basics and Preflight Requests

Understanding Cross-Origin Resource Sharing headers, simple vs preflighted requests, and the OPTIONS preflight mechanism.

CORS Basics and Preflight Requests

You'll learn how browsers extend the Same-Origin Policy through CORS headers and when they require permission before sending cross-origin requests.

What is CORS?

Cross-Origin Resource Sharing (CORS) is a mechanism that allows servers to explicitly permit cross-origin requests that would otherwise be blocked by the Same-Origin Policy (SOP). When your JavaScript tries to fetch data from a different origin, the browser checks if that server has given permission through special HTTP headers.

Think of CORS like a security guard at a restricted building. The SOP says "no visitors allowed," but CORS lets the building owner post a list saying "these specific visitors can enter."

Simple vs Preflighted Requests

Simple requests go through immediately if they meet basic criteria (like GET or POST with standard headers). The browser sends the request and checks the response headers to see if the server allows it.

Preflighted requests require extra caution. Before sending the actual request, the browser first sends an OPTIONS request (the "preflight") asking "is this okay?" This happens when:

  • Using methods like PUT, DELETE, or PATCH
  • Sending custom headers
  • Using non-standard Content-Type values

The Preflight Mechanism

The preflight OPTIONS request includes headers like:

  • Origin: where the request comes from
  • Access-Control-Request-Method: what method will be used
  • Access-Control-Request-Headers: what custom headers will be sent

The server responds with:

  • Access-Control-Allow-Origin: which origins are permitted
  • Access-Control-Allow-Methods: which methods are allowed
  • Access-Control-Allow-Headers: which headers are acceptable

Only if the server approves does the browser send the actual request.

Key Takeaway: CORS extends SOP by letting servers opt-in to cross-origin requests through headers, while preflight requests ensure complex operations are explicitly authorized before execution.