Codementor Events

How to enable CORS support on Lumen restapi web service

Published Nov 13, 2017Last updated Nov 15, 2017
How to enable CORS support on Lumen restapi web service

This time I would like to share my experience on how to enable CORS support on Lumen restapi web service, step by step.

Before going further, we must make sure that we have a working Lumen rest api service. You can learn here at https://paulund.co.uk/creating-a-rest-api-with-lumen. By the way, I am using Lumen 5.5.

CORS (Cross-Origin Resource Sharing) is somewhat about sharing resource to client with different domain as web server. In the case here, I used Plunker site (client) to access my restapi server. Sample response of one of my restapi end point is depicted below and would be used at cors test here:

Sample json response

For enabling CORS support, I used a composer package called Barryvdh/Laravel-Cors. I also read tutorial about cors in hml5rocks. Ok, without further ado, lets begin the journey, step by step:

Require the barryvdh/laravel-cors package

composer require barryvdh/laravel-cors

Do the configuration

To allow CORS for all routes, add the HandleCors middleware to the global middleware (I choose this step):

Configure middleware

but if you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:

Configure route middleware

Create config folder manually inside Lumen project folder, by default, config folder does not exist in root folder and then copy [myrestapi_app]/vendor/barryvdh/laravel-cors/cors.php to [myrestapi_app]/config folder. I edited the config as follows, to enable access from Plunker site:

Configure CORS

To allow from any domain, we can set allowedOrigins to ['*']

Create web client on Plunker

Finally I create a web client at Plunker using XMLHttpRequest, check this plunk. The request would only be success if I set allowedOrigins to ['*'] or ['https://run.plnkr.co'].

Sample success alert:

Sample success alert

Failed alert:

Failed alert

Chrome developer tools console would log this message:

Chrome developer tools console CORS error log

That's all the stories. I hope you enjoyed it ^_^

Discover and read more posts from Cipto Hadi
get started
post commentsBe the first to share your opinion
rully martanto
6 years ago

Hei, Which version lumen do you use ? I didn’t see config folder in my lumen.

Cipto Hadi
6 years ago

Lumen 5.5, thank you for your comment

Cipto Hadi
6 years ago

Sorry, what I mean with
“And then copy manually[myrestapi_app]/vendor/barryvdh/laravel-cors/cors.php to [myrestapi_app]/config folder”,
is to create config folder manually inside Lumen project folder and then copy the cors.php config file. I have updated the article accordingly.Thanks

Show more replies