API security and CORS: a NodeJS implementation

NodeJS logo

What is CORS

By default, browsers will block certain requests if both the client and the server are not in the same origin. Cross-origin resource sharing (CORS) is a specification designed to allow restricted resources from a remote server in a given origin, to be requested by a client associated to a different origin. An origin, as defined by the RFC6454, implies “identical schemes, hosts and ports”.

Usually the request from the browser will be accompanied by its corresponding HTTP headers, including the request’s origin. Example of the HTTP headers on the request:

Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:3001/
Origin: http://localhost:3001
Connection: keep-alive
Cache-Control: max-age=0
If-None-Match: W/”10-iv0euXUvX8F10Ha2yy45d6DFMcI”

How does CORS work?

When CORS is not enabled, the response will not contain the Access-Control-Allow-Origin header and the browser will likely block it, as illustrated by the diagram below.

You will notice that although both the API and the client are in the same domain, the different HTTP ports result in both having different origins.
Read more “API security and CORS: a NodeJS implementation”