How are CORS managed?

Question

How are CORS managed?

Question

As we may know (like we can see from this article) CORS or Cross-Origin Resource Sharing, is a manager for security policies on requests between different origins, ie. from website-A to website-B.

The CORS library we require in express builds an array of objects with very specific key/value pairs that are related to how HTTP and HTTPS request/response protocols are made.

For example, when we just say:

app.use(cors())

in our server file, we are requesting the default values from CORS to implement to every request in every route, that header created by CORS would look more-less like this:

{ 
  headers: [{'Access-Control-Allow-Origin':'*'},
    {'Access-Control-Allow-Credentials': true},
    {'Access-Control-Expose-Headers': 'FooBar'},
    {'Access-Control-Allow-Methods': 'GET,HEAD,PUT,PATCH,POST,DELETE'},
    {'Content Lenght': 0}
  ]
}

That headers array is read by web protocols that based on those values will process the communication between those two sites accordingly.

As a break down the main important keys are 'Access-Control-Allow-Origin' that when paired to a wildcard(*) it will accept requests from any origins, the same way 'Access-Control-Allow-Methods' sets how which type of requests are accepted.

That is how CORS are implemented and managed not just in general but also what the library cors do in express.

3 Likes