JavaScript Interview Question #136

What is CORS?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

CORS, or Cross-Origin Resource Sharing, is an HTTP-based browser security mechanism that allows a server to indicate which other origins may access its resources through browser scripts.

Detailed Explanation

CORS, or Cross-Origin Resource Sharing, is an HTTP-based browser security mechanism that allows a server to indicate which other origins may access its resources through browser scripts.

For cross-origin requests that require permission, the browser checks CORS response headers. Some requests trigger a preflight OPTIONS request before the actual request. CORS is primarily configured by the server; adding arbitrary client-side headers cannot bypass a server's CORS policy.

Code Example

// Browser request from one origin to an API on another origin:
const response = await fetch(
    "https://api.example.com/products"
);

// The API must return suitable CORS headers
// for the requesting origin when required.