Recently we released laravel-cors. This package can add the necessary CORS headers of your Laravel app. In this post I'd like to give a quick explanation of what CORS is and how you can use the package.

What is CORS #

Imagine that all JavaScript code for domain X running in a browser would be able to make http requests to an domain Y. Malious code on domain X would be able to interact with site Y without you knowing. In most circumstances you don't want this. Luckily all major browsers only allow sites to make requests against their own domain. They don't allow JavaScript code to make request against a sites on different domains. This is called the same-origin policy.

But there are some scenarios where you do want to allow that behaviour. Think of an API running on domain X that you want to consume via JavaScript running on domain Y. CORS stands for cross-origin resource sharing. It's a standardized way to legitimately poke some holes in the same-origin policy.

Simple requests #

When JavaScript running on domain X performs a HEAD GET or certain POST request (with application/x-www-form-urlencoded, multipart/form-data or text/plain to domain Y the browser will add an Origin header. The application running on domain Y can use this header to check if the request is permitted. If the server responds with a header Access-Control-Allow-Origin containing the domain X then the browser will conclude that request was allowed. If the server didn't do that most browsers won't allow the JS on domain X to perform any requests towards domain Y.

All other requests #

All requests covered by the previous section will probably only be used to retrieve some data. All other ones such as certain POST requests, PUT, PATCH, DELETE will probably modify existing data on the server. For those kinds of request the browser will send a preflight request before doing the actualy request.

This preflight request using the OPTIONS verb.