Skip to main content

What is CORS? (Cross-Origin Resource Sharing)

This is a mechanism that you will start to encounter when you enter a project already in place or simply having a React front for example with an API in back via node.

In ultra simplified terms: it is a mechanism that allows HTTP requests to be secured between two different domains.

That's to say ?

If you have a front on a domain or port 3000 locally and a back on another domain / on port 3001, CORS will help secure HTTP requests between these two domains. So basically the two domains cannot communicate with each other, CORS will help secure this communication and be able to connect your front to your back-end.

What is CORS?

CORS is a security policy in web browsers. It works a bit like a gatekeeper that decides what information can be shared between different websites.

Imagine that each website is a house. CORS is the rule that determines whether residents of one house can interact with those of another house. Why and When do you need CORS? You need CORS when you develop web applications that interact with servers located on different domains.

Security: CORS prevents malicious scripts from other sites from reading or modifying sensitive data. Resource Sharing: It allows developers to control how resources are shared between different sites in a secure manner.

Implementation of CORS

To configure CORS, you must set specific HTTP headers on your server. These headers tell the browser whether a request from different domains can be accepted or not.

Set Authorized Origin

Access-Control-Allow-Origin: Here you specify which domain can access the resources. For example, Access-Control-Allow-Origin: * allows all domains to access resources.

Set Allowed Methods

Access-Control-Allow-Methods: Specifies the HTTP methods (GET, POST, PUT, etc.) allowed for resource access.

Set Allowed Headers

Access-Control-Allow-Headers: Lists specific HTTP headers that requests can use.

Fundamentals to Know about CORS

Query Types

Simple Queries

Use GET, POST, or HEAD methods without special HTTP headers.

Pre-checked queries (Preflight)

Require additional checking (OPTIONS request) for methods other than GET, POST, or HEAD, or with custom HTTP headers.

CORS Error Handling

CORS errors occur when the browser blocks a request due to broken CORS rules. Example error: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

Best Practices

Do not set Access-Control-Allow-Origin: * for sensitive resources, as this opens access to everyone. Make sure CORS configurations are correct and tested to avoid security issues.

Process with node/express + react

Back-End Node.js

  • Installing CORS via NPM:
npm install cors
  • Configuring CORS in your Express Application: in the main Node.js server file:
const express = require('express');
const cors = require('cors');

const app = express();


// Configuration CORS
app.use(cors({
origin: 'http://localhost:3000' // Remplacez par le port de votre front-end React
}));

// Vos routes et middlewares ici

const port = process.env.PORT || 3001;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

Front-End React

In your React application, when making requests to the backend, specify the full URL of the backend. For example, using fetch or axios:

fetch('http://localhost:3001/api/data') // Remplacez par le port local de l'API Node
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

With Axios

axios.get('http://localhost:3001/api/data')
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));

Production Environment

When you deploy your application, don't forget to update the URLs of your React application and your Node.js API.