Skip to main content

Understanding CORS (Cross-Origin Resource Sharing)

CORS appears when a web page requests a resource from another origin — a different scheme, domain or port. A front end on http://localhost:3000 and an API on http://localhost:3001 are distinct origins.

CORS is an HTTP-header protocol through which a server tells the browser which origins may read its responses. The browser may send some requests without prior permission, but it only exposes the response to the script when the headers are compatible.

The security boundary to remember

CORS complements the browser same-origin policy. It does not replace authentication, authorization or CSRF protection, and it does not necessarily prevent a request from being sent. Server-to-server requests are not blocked by CORS.

Main headers

  • Access-Control-Allow-Origin permits one explicit origin or, for a public resource without credentials, *.
  • Access-Control-Allow-Methods lists accepted methods.
  • Access-Control-Allow-Headers lists accepted headers.
  • Access-Control-Allow-Credentials: true permits cookies or credentials with an explicit origin; it is incompatible with Access-Control-Allow-Origin: *.

Simple requests and preflight

A request is “simple” only when its method, headers and Content-Type all meet the safelist criteria. For other requests, the browser first sends OPTIONS to check the origin, method and requested headers.

A CORS error appears in the console when the browser refuses to expose a response, for example: No 'Access-Control-Allow-Origin' header is present….

Best practices

  • Allow an explicit origin list when a response contains private data.
  • Validate authentication, authorization and CSRF protection separately.
  • Test simple requests, preflights, credentials and error responses.

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' // Replace with your React front-end origin
}));

// 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') // Replace with your local API origin
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return 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.