From invoices to contracts, get notified on time, every time, across email, SMS, and WhatsApp Get Started in Minutes

Solving CORS Issues in Multi-Domain FilamentPHP Applications

Solving CORS Issues in Multi-Domain FilamentPHP Applications
Solving CORS Issues in Multi-Domain FilamentPHP Applications

Recently, I encountered a CORS issue while working with FilamentPHP in a multi-domain application. This was because I had configured my application to use multiple domains. I wanted to display resources like PDF files, images, and videos from the main domain within one of the subdomains.

As expected, I encountered the familiar "CORS error":

Resource from origin 'https://myrootdomain.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No Access-Control-Allow-Origin header is present on the requested resource.

Even though I had already configured Laravel's CORS settings and set the APP_URL environment variable correctly, the error persisted. This led me to investigate further.

Understanding the Cause

The key to understanding this issue lies in how static resources are handled. When you request a static resource like an image or PDF, the web server directly serves it without involving the Laravel application and its middleware. This means that Laravel's CORS middleware, which normally adds the necessary CORS headers, is bypassed.

The Culprit: Filepond

It's important to note that Filament uses the Filepond library for managing media and file uploads. Filepond, by default, requests static assets like file previews using absolute URLs, which can lead to CORS issues if the resource is served from a different domain than the main application.

The Solution: Adding CORS Headers Manually

To resolve this issue, we need to manually add CORS headers to your server configuration. If you're using NGINX, you can add the following snippet to your server block:

location ~ \.(bmp|cur|gif|ico|jpe?g|png|svgz?|webp|pdf)$ {
    add_header Access-Control-Allow-Origin *;
}

This configuration matches any file ending with the specified extensions and adds the Access-Control-Allow-Origin header with a value of *, allowing access from any origin.

Important Note:

While setting Access-Control-Allow-Origin: * is convenient for development and testing, it's essential to restrict the allowed origins to specific values in production environments for security reasons. You should only allow origins from your trusted domains.

Additional Considerations:

If you're using a different web server like Apache, the configuration syntax will vary. 

Stay on Top of Every Deadline

Never worry about missing an important date again—track your contracts, licenses, and warranties with ease!