Implementing cross-origin resource sharing (CORS) using middleware in CakePHP 3.3

I worked on a project recently where I had to allow XMLHttpRequests from a different domain. I initially thought about adding the necessary Access-Control headers at the controller level, but after doing some reading, it turned out it was a better idea to make use of a dispatcher filter. However, dispatcher filters would only apply prior to CakePHP 3.3 since they are now deprecated.

Enter middleware, which I found to be quite familiar since I have made use of a similar concept in Express during my Node.js development. Think of middleware as reusable components which you can use to handle your web requests and modify responses.

The CakePHP middleware classes should be placed in the src/Middleware folder. You can create the folder if it doesn’t already exist in your project.

We’ll create a class in the Middleware folder called CorsMiddleware.php.

The code listing is pretty straightforward. The response is modified with the necessary headers to enable the cross origin requests to be successfully handled by the browser.

You can modify the header values as you see fit, like limiting the Access-Control-Allow-Origin header to specific domains – the wildcard (*) allows requests to be accepted from all domains – or the the request methods to just GET and POST, or the allowed request headers.

To make use of the cors middleware, modify src\Application.php and add the middleware using:
$middleware->add(new CorsMiddleware())

And that’s all there is to it. There are more details about what you can do with middleware in the CakePHP documentation, so be sure to check it out.