Skip to content

CORS, Cross-Origin Resource Sharing

The Valley of Code

Your Web Development Manual

An introduction to Cross-Origin Resource Sharing, the way to let clients and servers communicate even if they are not on the same domain

A JavaScript application running in the browser can usually only access HTTP resources on the same domain (origin) that serves it.

Loading images or scripts/styles always works, but XHR and Fetch calls to another server will fail, unless that server implements a way to allow that connection.

This way is called CORS, Cross-Origin Resource Sharing.

Also loading Web Fonts using @font-face has same-origin policy by default, and other less popular things (like WebGL textures and drawImage resources loaded in the Canvas API).

One very important thing that needs CORS is ES Modules, recently introduced in modern browsers.

If you don’t set up a CORS policy on the server that allows to serve 3rd party origins, the request will fail.

Fetch example:

Fetch failed because of CORS policy

XHR example:

XHR request failed because of CORS policy

A Cross-Origin resource fails if it’s:

and it’s there for your security, to prevent malicious users to exploit the Web Platform.

But if you control both the server and the client, you have all the good reasons to allow them to talk to each other.


It depends on your server-side stack.

Browser support

Pretty good (basically all except IE<10):

CORS browser support

Example with Express

If you are using Node.js and Express as a framework, use the CORS middleware package.

Here’s a simple implementation of an Express Node.js server:

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

app.get('/without-cors', (req, res, next) => {
  res.json({ msg: '😞 no CORS, no party!' })

const server = app.listen(3000, () => {
  console.log('Listening on port %s', server.address().port)

If you hit /without-cors with a fetch request from a different origin, it’s going to raise the CORS issue.

All you need to do to make things work out is to require the cors package linked above, and pass it in as a middleware function to an endpoint request handler:

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

app.get('/with-cors', cors(), (req, res, next) => {
  res.json({ msg: 'WHOAH with CORS it works! 🔝 🎉' })

/* the rest of the app */

I made a simple Glitch example, here’s its code:!/flavio-cors-client.

This is the Node.js Express server:!/flaviocopes-cors-example-express

Note how the request that fails because it does not handle the CORS headings correctly is still received, as you can see in the Network panel, where you find the message the server sent:

No response from CORS

Allow only specific origins

This example has a problem however: ANY request will be accepted by the server as cross-origin.

As you can see in the Network panel, the request that passed has a response header access-control-allow-origin: *:

The CORS response header

You need to configure the server to only allow one origin to serve, and block all the others.

Using the same cors Node library, here’s how you would do it:

const cors = require('cors')

const corsOptions = {
  origin: '',

app.get('/products/:id', cors(corsOptions), (req, res, next) => {

You can serve more as well:

const whitelist = ['', '']
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))


There are some requests that are handled in a “simple” way. All GET requests belong to this group.

Also some POST and HEAD requests do as well.

POST requests are also in this group, if they satisfy the requirement of using a Content-Type of

All other requests must run through a pre-approval phase, called preflight. The browser does this to determine if it has the permission to perform an action, by issuing an OPTIONS request.

A preflight request contains a few headers that the server will use to check permissions (irrelevant fields omitted):

OPTIONS /the/resource/you/request
Access-Control-Request-Method: POST
Access-Control-Request-Headers: origin, x-requested-with, accept

The server will respond with something like this(irrelevant fields omitted):

HTTP/1.1 200 OK
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE

We checked for POST, but the server tells us we can also issue other HTTP request types for that particular resource.

Following the Node.js Express example above, the server must also handle the OPTIONS request:

var express = require('express')
var cors = require('cors')
var app = express()

//allow OPTIONS on just one resource
app.options('/the/resource/you/request', cors())

//allow OPTIONS on all resources
app.options('*', cors())
→ Read my DOM Tutorial on The Valley of Code
→ Read my Browser Events Tutorial on The Valley of Code
→ Read my Browser APIs Tutorials on The Valley of Code
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)