Home » Laravel » How to Use CORS in Laravel

How to Use CORS in Laravel

CORS (Cross-Origin Resource Sharing) is a mechanism that lets the web server allow or restrict fetching of its resources from other domains. For example, you can allow browsers to fetch your scripts and images only if your site is opened in the browser. If someone tries to insert links to your images on their website, this person will get a CORS error. It is a default behavior.

But if you want to allow any service to interact with your server, configure CORS. In many cases, CORS are configured at the web server level, for example, Nginx or Apache. But if you want more flexible configuration, you can handle it at the application level. In this article, we will explain how to use CORS in Laravel.

How to Configure CORS in Laravel

There are two ways to handle CORS in Laravel. You can use the fruitcake/laravel-cors package or you can add CORS headers manually. The package can cover 90% of your requirements. It allows configuring CORS only for specific paths and adding multiple domains. But if you want something special, don’t forget, that CORS are simple headers and you can return what you want using the withHeaders() method of the Response class.

1. Configuring package

First, install the fruitcake/laravel-cors package in your project using this command:

composer require fruitcake/laravel-cors

Next, open app/Http/Kernel.php and add the HandleCors middleware into the $middleware array:

protected $middleware = [ \Fruitcake\Cors\HandleCors::class, // … ];

After this, publish the package configuration using the following command:

php artisan vendor:publish --tag="cors"

Open the config/cors.php config file and find paths directive. Here, you can specify path patterns which should have CORS headers. By default, it is allowed only for API:

'paths' => ['api/*', 'sanctum/csrf-cookie']

Next, find allowed_origins. Here, you can specify the domains which will be able to interact with your server. Or you can specify “*” symbol for all domains.

Also you can use allowed_origins_patterns if you want to match the domain using preg_match() regular expression. It can work with allowed_origins because the application can send only one domain to the header, so in any case, the middleware will look at the current origin and if it matches with one of domains in lists, it will send it as allowed origin. Is uses this code for checking it:

$origin = (string) $request->headers->get("Origin"); if (in_array($origin, $this->allowedOrigins)) { return true; } foreach ($this->allowedOriginsPatterns as $pattern) { if (preg_match($pattern, $origin)) { return true; } }

Let’s look at the example. If you allow domain http://localhost:8080 and, you will get a header with the requested domain:

If you want to allow credentials for CORS, set supports_credentials to true in the config file. By default, there are no cookies in API requests, but if you want you can allow using cookies on the frontend side. If you use the fetch() method, you do something like this:

fetch("https://domain/path", { credentials: "include" });

But if you want it to work with cross-domain requests, enable credentials for CORS. Note, that you can’t use ‘*’ for allowed_origins when credentials are enabled.

2. Configuring manually

If you want to send different CORS settings to the client depending on the request parameters or settings in the database, do it manually because the package allows adding CORS settings only globally. But it is not so difficult. Also, you can use both the package and manual method, because the middleware from the package will set headers after the controller returns the response, and if the response already has the CORS headers it just leaves it as is.

Note, that this behavior is characteristic only of the fruitcake/laravel-cors package. If you use a built-in middleware or another package, it may work differently.

If you want to send a specific domain to the user, create a response using the response() helper and withHeaders() to send the Access-Control-Allow-Origin header. For example, haait.net:

$response = response(); $response->withHeaders([ "Access-Control-Allow-Origin" => "https://haait.net", ]); return $response;

Also, you can send the current origin if it matches with specific pattern:

$origin = $request->headers->get("Origin"); if (Str::endsWith($origin, "haait.net")) { $response->withHeaders([ "Access-Control-Allow-Origin" => "https://haait.net", ]); } return $response;

You can check headers using the developer console in your browser or the curl command.

Wrapping Up

In this article we have explained how to configure CORS in Laravel using package, or how to set CORS manually for a specific request. It may be helpful if you are creating REST APIs for external services. You can read more about creating REST API here.

Your Reaction

Leave a Comment