CORS: What It Is and How It Works

Home » Blog » Software » Front End Development » CORS: What It Is and How It Works

Expanding on last week’s article on best practices for REST API Design I’d like to point to a specific aspect working REST APIs frequently entails: A browser security feature called “Cross-Origin Resource Sharing (CORS)“.

This feature allows you to define which resources provided by a web application are supposed to be accessible from which origin, which in turn typically is comprised of protocol, host / domain name and port. This website’s origin for example is https://bjoernkw.com:80 (port 80 is the default port for HTTP, which browsers usually hide from the user).

In a nutshell, this prevents malicious actors from accessing or siphoning off potentially sensitive data by spoofing a legitimate website under a different domain name.

While CORS certainly is a useful – even vital – security feature it also comes with pitfalls, particularly when you’re developing a web application with separate front-end and back-end components.

Back in day, when user-facing view code was largely generated on and provided by the same server that also was responsible for the back-end business logic this wasn’t much of a problem since in those cases the origin most of the times was the same for both the view layer and the underlying business logic layers. With the advent of single-page applications (SPAs) and back-end applications serving REST API endpoints that changed, however, because we now often have different hosts or ports for the front-end and back-end parts of our application. While this issue usually is alleviated in production by running the different components of an application behind a reverse proxy (hence, producing a single, unified user-facing host) the problem remains during development where we often have separate processes for our front-end and our back-end running on the same host but under different ports (e.g. http://localhost:4200 for an Angular front-end and http://localhost:8080 for a Java application).

In those cases, we still need to deal with CORS, which is another reason why web developers should know about its ins and outs.

This recent article by Ilija Efitmov covers everything from how CORS came about to how to properly make use of it, including best practices and potential snags you might hit: Deep dive in CORS: History, how it works, and best practices

The server-side examples shown in the article are written in Crystal but concepts they exemplify are language- and framework-agnostic. So, no matter what technologies you use for developing back-end applications and providing REST APIs the principles, practices, and techniques outlined there still apply.

About the author: Bjoern
Independent IT consultant, entrepreneur

Leave a Comment