Steps to enable CORS on a Lumen API Backend

Published Nov 24, 2017
Steps to enable CORS on a Lumen API Backend

CORS simply refers to Cross Origin Resource Sharing. CORS is a technique that uses HTTP requests to let a browser on one origin(a domain) gain access to a resources on a different origin. By default, a technique known as the Same-Origin policy is used to prevent your javascript code from making ajax requests to a different domain. This is a very good security measure but a lot of times, gets in the way of gaining legitimate access to needed resources.

Step 1: Set up a CORS middleware.

In your app\Http\Middleware folder, create a new php class and save the filename as CorsMiddleware.php. Of course, you can call it anything you want. Just don't forget it 😃.
In your new class, add the following lines of code:

<?php
namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];

        if ($request->isMethod('OPTIONS'))
        {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
        {
            $response->header($key, $value);
        }

        return $response;
    }
}

Here, we are setting up a middleware which will be responsible for interception of all requests to your API. You'll notice that we are checking for the OPTIONS request explicitly and returning access control headers alongside a status code of 200. Sometimes, your user-agent (browser) sends an OPTIONS request first as a form of verification request. However, lumen, somehow, does not recognize the OPTIONS request method and rejects it with a 508. Hence the need to specifically check this request and grant it access.

Step 2: Register your new middleware

Head over to your bootstrap/app.php file and register your new middleware with the following lines:

$app->middleware([
    App\Http\Middleware\CorsMiddleware::class
 ]);

Place this in the Middleware Registration Section. Remember to change the CorsMiddleware part to reflect the name of your middleware class if you named it differently earlier.

That's about it, you can now send those axios requests!

Don't forget to drop your comments and reactions. Thank you.

Happy Coding - DevMelas

Discover and read more posts from Chiemela Chinedum
get started