Back to all questions

What is CORS and how does it work?

Devs Hive

Devs Hive

Seen on interview: 1 user

CORS (Cross-Origin Resource Sharing) is a mechanism that lets a server tell the browser which websites are allowed to read its responses.

Imagine we’re building an online store:

  1. The frontend runs on shop.com.
  2. The backend runs on api.shop.com.

When the website requests a list of products, the browser notices that the request goes to a different domain. By default, it won’t let JavaScript read the response without permission from the server.

This is where CORS comes in. The backend adds a special response header that effectively says: “I allow shop.com to read my responses.” The browser checks this permission and makes the data available to the website’s code.

If permission is missing or configured incorrectly, you’ll see the familiar CORS error in the console.

Why is this needed?

To prevent code on a random website you visit from freely reading data from other websites where you’re logged in.

One important detail: the browser enforces these restrictions. CORS doesn’t replace authorization or prevent requests from Postman or another server.

Seen on interview?

Related Questions

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!