Skip to main content

Command Palette

Search for a command to run...

Understanding CORS: What Is It and Why It Matters.

Mastering Cross-Origin Resource Sharing: A Guide to Implementing and Understanding CORS?

Updated
3 min read
Understanding CORS: What Is It and Why It Matters.
S

Hey 👋🏻, I am , a Software Engineer from India. I am interested in, write about, and develop (open source) software solutions for and with JavaScript, ReactJs. 📬 Get in touch

Twitter: https://x.com/SankalpHaritash Blog: https://sankalp-haritash.hashnode.dev/ LinkedIn: https://www.linkedin.com/in/sankalp-haritash/ GitHub: https://github.com/SankalpHaritash21

📧 Sign up for my newsletter: https://sankalp-haritash.hashnode.dev/newsletter

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to prevent malicious websites from accessing resources and data from another domain without permission. It acts as a safeguard against certain types of cyber attacks, such as Cross-Site Scripting (XSS) and data theft, by enforcing a same-origin policy. However, while the same-origin policy restricts web pages from making requests to a different domain, CORS provides a controlled way to relax this policy under certain conditions deemed safe by the resource owner.

Understanding CORS Policy

At its core, the CORS policy allows servers to specify who can access their resources and under what conditions. This is done through the use of HTTP headers that define the parameters under which cross-origin requests are permitted. The most important of these headers include:

  • Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource.

  • Access-Control-Allow-Methods: Specifies the methods (GET, POST, PUT, etc.) that are allowed when accessing the resource.

  • Access-Control-Allow-Headers: Specifies the headers that can be used during the actual request.

Significance of CORS in Web Security

The significance of CORS in web security cannot be overstated. Without CORS, websites would be much more vulnerable to attacks where malicious actors could steal sensitive data, impersonate users, and perform unauthorized actions by exploiting the credentials of unsuspecting users. By allowing web applications to control how and when cross-origin requests can be made, CORS plays a crucial role in the security infrastructure of the modern web.

Real-Life Use Case

Imagine a scenario where you have two domains: https://www.example.com, which hosts your main web application, and https://api.example.com, which serves as your application's API endpoint. In a situation where your web application needs to make AJAX requests to your API, CORS policies come into play. Without proper CORS headers set on your API responses, browsers will block these cross-origin requests for security reasons.

Implementing CORS

Server-Side Implementation

On the server side, implementing CORS typically involves setting the appropriate headers in your responses. Here's a basic example in Node.js using the Express framework:

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

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'https://www.example.com'); 
// Allow only https://www.example.com to access the resources
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE,
 OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, 
Content-Type, Accept, Authorization');
    next();
});

app.get('/data', (req, res) => {
    res.json({ message: 'This is CORS-enabled for a single origin.' });
});

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

This example demonstrates a basic setup where only requests from https://www.example.com are allowed to access the /data endpoint, and only certain HTTP methods are permitted.

Client-Side Usage

On the client side, using CORS is mostly about making sure your web application respects the CORS policy set by the server. When using modern web APIs like fetch or libraries like Axios to make HTTP requests, the browser automatically handles CORS compliance based on the server's responses.

Here's a simple example using the fetch API:

fetch('https://api.example.com/data', {
    method: 'GET', // or 'POST', 'PUT', etc.
    headers: {
        'Content-Type': 'application/json',
        // Additional headers can be specified here
    },
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

In this example, a web application making a request to https://api.example.com/data will succeed if the CORS policies of api.example.com allow requests from the origin of the web application. Otherwise, the browser will block the request and log an error in the console.

Summary:

CORS is a critical component of web security, enabling secure cross-origin requests while preventing unauthorized access and data breaches. Properly configuring CORS policies on your server and understanding how to handle cross-origin requests on the client side are essential skills for web developers. By adhering to these standards, you can build more secure and interoperable web applications.

J

CORS is in no way a critical component of web security. If anything, CORS is a major pain for web developers. CORS does not prevent unauthorized access, does not prevent data breaches and instead it bugs the web developers over nothng. Only web browsers respect CORS because CORS' major fault is that is a client-side "security" measure. This means that you can (very easily) use a client that does not follow the rules. The perfect example is Postman. So where is the security? Nowhere to be found.

1
S

Good afternoon sir,

Sir These are my tought on CORS as its aim is to allows data exchange only between whitelisted websites as specified by the server, which is designed to enhance security by restricting which domains can interact with certain APIs or resources. However, there are indeed methods to bypass CORS, such as using a proxy server or modifying headers with certain tools during development, which can help developers test their applications.

I have used the Swiggy real API, they have blocked all direct access by using CORS, developers often need to use server-side code to interact with the API instead of making these calls directly from the client-side. This not only complies with CORS but also helps maintain security by keeping API keys and credentials server-side, away from the client.

As for implementing authentication, CORS does not directly interfere with authentication mechanisms. Authentication and authorization can still be handled as usual via tokens, sessions, or other methods, which are then included in cross-origin requests once CORS policies allow these requests. The server that handles the request will still perform authentication checks regardless of the origin of the request, ensuring that access control is maintained.

Yes sir I know that CORS is like burden during development, but it also serves as a crucial part of securing applications by controlling access based on origins, which helps prevent unwanted or malicious interactions.

1
J

SANKALP HARITASH The whole point of investing time learning CORS as a developer is to achieve a better product, but one cannot. You are saying your "aim is to allow data exchangew between whitelisted websites", but that's the thing! CORS cannot whitelist!! Open postman, do direct queries and that's it, you're obtaining data and your Postman is not part of the whitelist. My point being: CORS is mostly a waste of time. CORS cannot stop any form of data theft because the server will volunteer the data every time, be it a whitelisted site or not.

S

Yes Sir you are right these tools like postman don't respect the rules implemented by CORS this is one of the limitation of CORS

J

SANKALP HARITASH Yes, and just by the existence of this possibility (tools that don't give a darn about CORS) is what makes CORS a pretty much useless feature. In the end CORS exists to annoy legitimate users of your API. That's it. Security where? Nowhere. Even web browsers have a way to turn off CORS. You don't even need Postman or anything else. Just run Chrome with security turned off.

So my point being: CORS doesn't work because it cannot deliver, and I believe your article is just following the trend of praising CORS when in fact there is nothing to praise. I get it, it is what all authors do. Still: It would be refreshing to read the real truth about CORS instead of the usual lies.

S

José Pablo Ramírez Vargas My article is about what I've learned; it's not about following trends. I'm sharing what I've discovered and what I'm learning as a student. While I may have missed some points, it doesn't mean I'm sharing false information. I'm not an author; I'm a student writing for my own benefit. If anyone wants to learn along with me, they're welcome to join.

There's a quote that resonates with me: "Being a developer takes time; it's not a piece of cake that can be eaten in a minute.

S

I am using this platform as a documentation of my learning. Sir if you find these article useless no need to read it. and if you can help me in improving then you are welcome.

System Design

Part 23 of 48

This page provides comprehensive information on system design, covering key concepts, best practices, and practical examples.

Up next

Enhancing Web Application Security with Web Application Firewalls?

How WAFs Work: Understanding the Mechanisms Behind Web Application Protection

More from this blog

Sankalp's blog

96 posts

Hey there! I'm Sankalp Haritash, a passionate Full Stack Developer skilled in MERN stack. Crafting immersive experiences, embracing innovation, fostering collaboration, and also a writer.