DEV Community

Cover image for Introduction to CORS: Understanding the Basics with Practical Examples
Dipak Ahirav
Dipak Ahirav

Posted on • Updated on

Introduction to CORS: Understanding the Basics with Practical Examples

In the world of web development, CORS (Cross-Origin Resource Sharing) is an essential concept that developers must understand to ensure secure and efficient data exchange between different domains. This guide will take you through the intricacies of CORS, explaining its purpose, how it works, and providing practical examples to solidify your understanding.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

What is CORS?

CORS is a security feature implemented by web browsers to control how web pages can request resources from a different domain than the one that served the web page. This is crucial for preventing malicious websites from accessing sensitive data from another site.

Why is CORS Important?

CORS allows servers to specify who can access their resources and how they can be accessed. Without CORS, websites would be unable to interact with APIs or resources on different domains, severely limiting the functionality of modern web applications.

How CORS Works

When a web page makes a request to a different domain (a cross-origin request), the browser sends an HTTP request with an Origin header. The server then responds with specific CORS headers to indicate whether the request is allowed. Here are the main headers involved:

  • Access-Control-Allow-Origin: Specifies which origins are permitted to access the resource.
  • Access-Control-Allow-Methods: Indicates the HTTP methods allowed for the resource.
  • Access-Control-Allow-Headers: Lists the headers that can be used during the actual request.

Simple Request vs. Preflight Request

Simple Request

A simple request is one that meets certain criteria, such as using one of the GET, POST, or HEAD methods without custom headers. For these requests, the server responds directly with the appropriate CORS headers.

Preflight Request

For more complex requests (e.g., those that use methods other than GET/POST or include custom headers), the browser first sends an OPTIONS request to the server. This is known as a preflight request, and it checks whether the actual request is safe to send.

Example: Setting Up CORS in a Node.js Express Server

Let's walk through an example to see how CORS is implemented in a Node.js Express server.

Step 1: Set Up Your Node.js Project

First, create a new Node.js project and install the necessary dependencies:

mkdir cors-example
cd cors-example
npm init -y
npm install express cors
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Server

Create a new file named server.js and add the following code:

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

// Enable CORS for all routes
app.use(cors());

app.get('/data', (req, res) => {
  res.json({ message: 'Hello, CORS!' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

In this example, we use the cors middleware to enable CORS for all routes. This allows any domain to access the /data endpoint.

Step 3: Test the CORS Configuration

To test the CORS configuration, create an HTML file (index.html) with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CORS Test</title>
</head>
<body>
  <h1>Testing CORS</h1>
  <button id="fetchData">Fetch Data</button>
  <div id="result"></div>

  <script>
    document.getElementById('fetchData').addEventListener('click', () => {
      fetch('http://localhost:3000/data')
        .then(response => response.json())
        .then(data => {
          document.getElementById('result').textContent = data.message;
        })
        .catch(error => {
          console.error('Error:', error);
        });
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Open index.html in your browser and click the "Fetch Data" button. You should see the message "Hello, CORS!" displayed on the page.

Further Reading

To gain a more comprehensive understanding of CORS, including advanced topics and practical examples, check out our follow-up blog post: Advanced CORS: Deep Dive into Cross-Origin Resource Sharing.

Conclusion

Understanding and configuring CORS is crucial for modern web development. By setting the appropriate CORS headers, you can control how your resources are accessed, ensuring both security and functionality. This guide has provided a foundational understanding of CORS and a practical example to help you get started.

Start Your JavaScript Journey

If you're new to JavaScript or want a refresher, visit my blog on BuyMeACoffee to get started with the basics.

👉 Introduction to JavaScript: Your First Steps in Coding

Support My Work

If you enjoy my content and want to support my work, consider buying me a coffee! Your support helps me continue creating valuable content for the developer community.

Series Index

Part Title Link
1 Top 10 JavaScript Best Practices for Writing Clean Code Read
2 Top 20 JavaScript Tricks and Tips for Every Developer 🚀 Read
3 8 Exciting New JavaScript Concepts You Need to Know Read
4 Top 7 Tips for Managing State in JavaScript Applications Read
5 🔒 Essential Node.js Security Best Practices Read
6 10 Best Practices for Optimizing Angular Performance Read
7 Top 10 React Performance Optimization Techniques Read
8 Top 15 JavaScript Projects to Boost Your Portfolio Read
9 6 Repositories To Master Node.js Read
10 Best 6 Repositories To Master Next.js Read
11 Top 5 JavaScript Libraries for Building Interactive UI Read
12 Top 3 JavaScript Concepts Every Developer Should Know Read
13 20 Ways to Improve Node.js Performance at Scale Read
14 Boost Your Node.js App Performance with Compression Middleware Read
15 Understanding Dijkstra's Algorithm: A Step-by-Step Guide Read
16 Understanding NPM and NVM: Essential Tools for Node.js Development Read

Follow and Subscribe:

Top comments (17)

Collapse
 
brense profile image
Rense Bakker

I would like to stress here that CORS is in no way a tool that can be used to protect sensitive data on YOUR server! CORS headers only allow the browser to show a warning to the user, when the site they are looking at, is making requests to a different domain. For example when someone's trying to load google.com in an iframe to steal user login data. The google server has a CORS header, that allows the browser to detect this illegitimate usage and warn the user. If you use something other than a web browser to make a request to google.com CORS headers are completely ignored and you can get data from the resource without any problems.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you for pointing this out! I have addressed this misconception and provided more detailed information in a follow-up blog post. You can read it here: Advanced CORS: Deep Dive into Cross-Origin Resource Sharing. I hope this helps clarify things further.

Collapse
 
abrahamn profile image
Abraham

Good that you've taken time to write this but this is nowhere near comprehensive or a guide whatsoever. Good starting point for anyone should be on the w3c, web authority or MDN at developer.mozilla.org/en-US/docs/W...

Practical implementation on your server should be based on your server implementation

Collapse
 
ezpieco profile image
Ezpie • Edited

In dev.to we want no missleading content here, please change your title as per your content, this is not a non-programmer platform so clickbait doesn't work, we appreciate that you have put work into this, but due to it being misleading I will have to take actions as a mod, you blog has been marked as low quality. I hope you understand why and please change your title, it's too clickbait.

Collapse
 
samiekblad profile image
Sami Ekblad

Thanks for this article! One aspect of cross-site or cross-origin that is not discussed here is 3rd party cookies. They are not specifically needed for single resource fetch, but when you embedded more complex widgets or integrate applications.

Discussed that in my embedding article and did some experiments with the proposed changes in Chrome how to handle these scenarios.

Collapse
 
onoffrei profile image
onoffrei

Click bait

Collapse
 
dipakahirav profile image
Dipak Ahirav

I appreciate your feedback. To provide more comprehensive information, I have written a detailed follow-up blog post on CORS. You can read it here: Advanced CORS: Deep Dive into Cross-Origin Resource Sharing.

Collapse
 
chani_diakidis_b2ab80f78f profile image
Chani Diakidis

Sorry, but the title is really misleading. The article is far from a definitive guide and surely isn't enough to master CORS. It's merely an introduction to the topic if any.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you for your feedback! I understand your concern about the title. I have created a follow-up blog post that delves deeper into CORS and covers advanced topics. Please check it out here: Advanced CORS: Deep Dive into Cross-Origin Resource Sharing.

Collapse
 
bigwebdeveloper profile image
Azeez Ishola Oloto

I love this. But won't you run the server.js
Like
: node server.js

Collapse
 
sweetestshuga profile image
Eze Sugar 👩‍💻

You said cors is used to restrict access to the server. But then from the example you gave, it allowed access from everywhere, which I beleive is not a good example.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you for your feedback! @sweetestshuga . I understand your concern. The purpose of the example was to demonstrate how to enable CORS using the cors middleware in a simple way. You’re right that allowing access from everywhere ('*') isn't always a good practice, especially in a production environment.

To restrict access to specific domains, you can configure the cors middleware to allow only certain origins. Here’s an updated example that demonstrates this:

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

// Enable CORS for specific origins
const corsOptions = {
  origin: 'http://example.com', // Replace with your allowed origin
  methods: ['GET', 'POST'], // Replace with the allowed methods
  allowedHeaders: ['Content-Type', 'Authorization'], // Replace with the allowed headers
};

app.use(cors(corsOptions));

app.get('/data', (req, res) => {
  res.json({ message: 'Hello, CORS with specific configuration!' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sweetestshuga profile image
Eze Sugar 👩‍💻

Thanks for correction

Collapse
 
toby_bishop_1e3e470f385dc profile image
Toby Bishop • Edited

Great introduction to CORS! It's essential for web developers to grasp this concept for secure data exchanges across domains.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you so much @toby_bishop_1e3e470f385dc .for your positive feedback! I'm glad you found the introduction to CORS helpful. Understanding CORS is indeed crucial for secure data exchanges across domains. If you're interested in learning more about advanced CORS configurations and practical examples, feel free to check out my detailed follow-up blog post: Advanced CORS: Deep Dive into Cross-Origin Resource Sharing.

Collapse
 
codethumper profile image
Nycros First

I like the simple explanation. Much easier to understand the purpose of CORS.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you so much @codethumper