CORS

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that defines how data can be securely shared between different domains.

Meta Title:
CORS (Cross-Origin Resource Sharing) – Definition, How It Works, and Security | Glossary

Meta Description:
Learn what CORS (Cross-Origin Resource Sharing) is, how it works in web browsers, and why it is essential for secure API communication.

Meta Keywords:
CORS, cross-origin resource sharing, web security, same-origin policy, api, browser, javascript

CORS (Cross-Origin Resource Sharing)

CORS (Cross-Origin Resource Sharing) is a security mechanism in web browsers that controls how resources (such as APIs or data) can be shared between different domains.

By default, browsers block cross-origin requests (for example, requests from example.com to api.otherdomain.com) due to the Same-Origin Policy, which helps prevent attacks like Cross-Site Request Forgery (CSRF).

CORS allows servers to explicitly specify via HTTP headers which domains, methods, or headers are permitted to access their resources.

How CORS Works

  1. A web application on domain-a.com tries to load data from api.domain-b.com.
  2. The browser checks the Same-Origin Policy and, if necessary, sends a preflight request (using the HTTP method OPTIONS).
  3. The server responds with CORS headers such as:
Access-Control-Allow-Origin: https://domain-a.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
  1. If the response contains the proper permissions, the browser allows the request to proceed.

Important CORS Headers

  • Access-Control-Allow-Origin – Specifies which origins (domains) are allowed access.
  • Access-Control-Allow-Methods – Lists the allowed HTTP methods (e.g., GET, POST, PUT).
  • Access-Control-Allow-Headers – Lists additional allowed headers.
  • Access-Control-Allow-Credentials – Allows cookies/authentication data in cross-origin requests.

Example in Express.js (Node.js)

const express = require("express");
const cors = require("cors");

const app = express();
app.use(cors({ origin: "https://domain-a.com" }));

app.get("/data", (req, res) => {
  res.json({ message: "CORS enabled for domain-a.com" });
});

app.listen(3000, () => console.log("Server running on port 3000"));

Benefits of CORS

  • Enables secure data sharing across different domains.
  • Supports modern web applications that rely on APIs.
  • Protects against misuse enforced by the Same-Origin Policy.

Challenges

  • Misconfiguration – Overly broad rules (e.g., Access-Control-Allow-Origin: *) can create security risks.
  • Complexity – Preflight requests may add performance overhead.
  • Compatibility – Different browsers may behave slightly differently.

Conclusion

CORS is a central mechanism for secure and flexible web development. It enables controlled communication between different domains while protecting users from attacks.