DEV Community

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

Introduction to CORS: Understanding the Basics with Practical Examples

Dipak Ahirav on July 30, 2024

In the world of web development, CORS (Cross-Origin Resource Sharing) is an essential concept that developers must understand to ensure secure and ...
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