DEV Community

Cover image for What is CORS? : Explained
Akshay Chauhan
Akshay Chauhan

Posted on

What is CORS? : Explained

Understanding CORS: A Complete Guide

If you've ever built a web application that fetches data from another domain and encountered a CORS error, you're not alone! This guide will break down CORS, why it exists, how it works, and how to fix common CORS issues.

What is CORS?

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to restrict how resources are requested from different origins (domains, protocols, or ports). It prevents malicious websites from making unauthorized requests to a different domain on behalf of the user.

For example, if your frontend is hosted on https://myfrontend.com and tries to fetch data from https://api.mybackend.com, the browser blocks the request unless the backend explicitly allows it.

How CORS Works

Image description
To better understand how CORS works, it's helpful to look at a diagram. Consider a web page hosted on Domain A that wants to request data from a server hosted on Domain B.

When Domain A makes an HTTP request, the browser asks the server on Domain B if it can send the request from Domain A. This confirmation request is called a Preflight request.

The server on Domain B confirms whether it accepts requests from Domain A or not through CORS Headers (e.g. Access-Control-Allow-Origin, Allow-Control-Allow-Method, etc). Once the preflight request is successful, the browser makes the request to Domain B.

Let's say in another scenario the server on Domain B didn't allow any requests from Domain A. In that case, the browser blocks the request and returns an error. Hence Domain A is unable to access the said resource from the server on Domain B. That's precisely what CORS is.

History of CORS

Before CORS, web security relied on the Same-Origin Policy (SOP), introduced in the 1990s to prevent unauthorized access between different domains. The Same-Origin Policy restricted JavaScript from making requests to a domain different from the one that loaded the script.

The restriction protected user data, but also limited functionality, making it difficult for web applications to interact with APIs from different domains.

Why Was CORS Introduced?

As web applications became more dynamic and started integrating with third-party services (like APIs, cloud storage, and payment gateways), the Same-Origin Policy became too restrictive.

To allow safe cross-origin requests while maintaining security, browsers introduced CORS (Cross-Origin Resource Sharing) in the late 2000s.

CORS provides a way for servers to explicitly allow or deny requests from other domains using HTTP headers.

Major Security Incidents Before CORS

1. Cross-Site Request Forgery (CSRF) Attacks

Before CORS, attackers exploited CSRF vulnerabilities to trick users into performing unwanted actions on other websites where they were logged in.

🔴 Example: A Banking CSRF Attack

1️⃣ A user logs into their banking website (bank.com).
2️⃣ The user visits a malicious website (evil.com) in another tab.
3️⃣ The malicious website automatically sends a request to bank.com to transfer money, using the user's active session.
4️⃣ The banking website executes the request because it thinks the request is from the user (since the browser includes session cookies automatically).
5️⃣ Money is transferred without the user's knowledge!

🚨 Impact: Millions of dollars have been stolen using CSRF attacks on banking websites before proper security measures like CORS and CSRF tokens were widely implemented.

2. Data Theft via JSON Hijacking

Many websites used JSON data formats to transfer sensitive information. Before CORS, attackers could use malicious JavaScript to steal private JSON data.

🔴 Example: A JSON Hijacking Attack on a Shopping Website

1️⃣ The victim logs into shopping.com.
2️⃣ The attacker tricks the victim into visiting evil.com.
3️⃣ evil.com runs a malicious script that fetches order history from shopping.com.
4️⃣ Since browsers automatically attach authentication cookies, the request is successful.
5️⃣ The hacker now has access to the victim's shopping history and personal details.

🚨 Impact: Before CORS, many websites leaked sensitive user data because they did not restrict who could request their JSON APIs.

How CORS Works (With a Simple Analogy)

Think of a CORS request like trying to enter a restricted area:

1️⃣ You (frontend) want to visit a restricted building (backend API).
2️⃣ Security (browser) stops you and asks if you have permission.
3️⃣ The building manager (server) checks their records and says:

✅ "You're allowed!" → You enter.
❌ "You're NOT allowed!" → You're blocked.

This "permission" is handled using CORS headers in HTTP responses.

When a browser makes a cross-origin request, the server must include special headers in its response to allow the request.

Key CORS Headers and What They Do

Header Purpose Example
Access-Control-Allow-Origin Defines which domains can access the resource Access-Control-Allow-Origin: * (Allows all)
Access-Control-Allow-Methods Specifies allowed HTTP methods Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers Lists allowed custom headers Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age Caches preflight response (reduces requests) Access-Control-Max-Age: 86400 (24 hours)

Understanding Preflight Requests

Some CORS requests require an extra step called a preflight request.

When is a Preflight Request Sent?

  • If the request uses HTTP methods other than GET or POST (like PUT, DELETE).
  • If custom headers (e.g., Authorization) are included.
  • If sending non-simple content types (e.g., application/json).

How Preflight Works (Step by Step)

1️⃣ The browser first sends an OPTIONS request to check if CORS is allowed.
2️⃣ The server responds with CORS headers (if allowed).
3️⃣ If permitted, the browser sends the actual request.

Example Preflight Request:

OPTIONS /data HTTP/1.1
Origin: https://frontend.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
Enter fullscreen mode Exit fullscreen mode

Example Server Response:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://frontend.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
Enter fullscreen mode Exit fullscreen mode

How to Fix CORS Errors

✅ Solution: Add CORS Headers to the Server

Example: Fixing CORS in a Node.js Server:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors({
    origin: 'https://myfrontend.com',  // Allow only specific origin
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    credentials: true
}));

app.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

CORS is not just a technical headache — it's a vital security measure that prevents hackers from misusing your web applications. While it may seem annoying when developing web apps, proper CORS implementation ensures user safety and data protection.


Tags: #webdev #security #javascript #programming #cors

Top comments (1)

Collapse
 
akshay_chauhan profile image
Akshay Chauhan

Very Insightful