Laravel API + vue SPA : Cors probleme in subdomain multitenancy application
In a Laravel API + Vue.js Single Page Application (SPA) multitenancy setup, you might encounter CORS (Cross-Origin Resource Sharing) issues when making requests from the Vue.js application to the Laravel API on a subdomain. Here's a comprehensive and detailed answer to help you resolve this issue.
CORS is a security feature that restricts web pages from making requests to a different domain, except if the server explicitly allows it. In a multitenancy application, you might have multiple subdomains accessing the same Laravel API. To allow cross-origin requests, you need to configure the Laravel API and the Vue.js application accordingly.
- Laravel API Configuration:
To enable CORS in Laravel, you need to install the laravel/cors
package using Composer:
composer require laravel/cors
After installing the package, you need to register it in the app/Providers/AppServiceProvider.php
file:
use Laravel\Cors\CorsServiceProvider;
class AppServiceProvider extends ServiceProvider
{
protected $providers = [
// ...
CorsServiceProvider::class,
];
}
Next, you need to configure the CORS rules in the config/cors.php
file. You can define rules for specific subdomains or wildcard rules for all subdomains:
use Laravel\Cors\Rules\CorsRule;
protected $cors = [
'*' => [
'*' => ['access-control-allow-origin' => '*'],
],
// Specific subdomain rule
'api.tenant1.example.com' => ['*' => ['access-control-allow-origin' => 'api.tenant1.example.com']],
// Wildcard subdomain rule
'*.example.com' => ['*' => ['access-control-allow-origin' => '*.example.com']],
];
Replace api.tenant1.example.com
and *.example.com
with your actual subdomains.
- Vue.js Application Configuration:
In the Vue.js application, you need to configure the Axios instance to send the Access-Control-Allow-Origin
header with the Laravel API subdomain when making requests:
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com', // Laravel API subdomain
headers: {
'Access-Control-Allow-Origin': 'api.tenant1.example.com', // Your actual subdomain
},
});
export default api;
Replace https://api.example.com
with your actual Laravel API URL and api.tenant1.example.com
with your actual subdomain.
With these configurations, you should be able to make cross-origin requests from your Vue.js application to the Laravel API on a subdomain without encountering CORS issues.