tenancy icon indicating copy to clipboard operation
tenancy copied to clipboard

[Documentation] Missing Livewire 3 integration guide for Path identification

Open fdjkgh580 opened this issue 1 year ago • 4 comments

Bug description

Summary

The official documentation only covers Livewire integration with Domain identification, but lacks guidance for Path identification. This causes file upload failures and route caching issues in Path identification setups.

Current Documentation

https://tenancyforlaravel.com/docs/v3/integrations/livewire

All examples in the documentation use Domain identification:

// Current documentation example
Livewire::setUpdateRoute(function ($handle) {
    return Route::post('/livewire/update', $handle)  // No {tenant} prefix
        ->middleware('web', 'universal', InitializeTenancyByDomain::class);
});

The Problem

When using Path identification (InitializeTenancyByPath), Livewire file uploads fail with 419 CSRF errors and php
artisan optimize fails with route serialization errors.

Issue 1: File Upload 419 CSRF Errors

1. ✅ Update route can be customized via setUpdateRoute() to include /{tenant} prefix
2. ❌ Upload route (/livewire/upload-file) has no official API to customize
3. ❌ Preview route (/livewire/preview-file/{filename}) has no official API to customize

Error Details:

When uploading files from /tenant1/dashboard:
- Frontend sends POST to /livewire/upload-file (missing tenant prefix)
- SetSessionPathEarly middleware cannot extract tenant ID from URL
- Session cookie path remains / instead of /tenant1
- CSRF token validation fails → 419 error

Network Tab Evidence:

POST /livewire/upload-file
Set-Cookie: session_cookie; path=/  ❌ Wrong path

Should be:
POST /tenant1/livewire/upload-file
Set-Cookie: session_cookie; path=/tenant1  ✅ Correct path

Issue 2: Route Caching Fails (php artisan optimize)

When implementing the workaround by re-registering routes with the same name, php artisan optimize fails:

LogicException

Unable to prepare route [{tenant}/livewire/upload-file] for serialization.
Another route has already been assigned name [livewire.upload-file].

Root Cause:
- Livewire registers default routes (/livewire/upload-file)
- We register tenant routes (/{tenant}/livewire/upload-file)
- Both routes have the same name livewire.upload-file
- Route serialization doesn't allow duplicate names

Research Process

I analyzed the Livewire source code to understand the issue:

File: vendor/livewire/livewire/src/Features/SupportFileUploads/SupportFileUploads.php

class SupportFileUploads extends ComponentHook
{
    static function provide()
    {
        // These routes are registered globally without tenant prefix
        Route::post('/livewire/upload-file', [FileUploadController::class, 'handle'])
            ->name('livewire.upload-file');

        Route::get('/livewire/preview-file/{filename}', [FilePreviewController::class, 'handle'])
            ->name('livewire.preview-file');
    }
}

Key findings:
- Upload/Preview routes are hardcoded in the SupportFileUploads feature provider
- No official API like setUploadRoute() or setPreviewRoute() exists
- The only workaround is to manually re-register routes AND remove default routes

Complete Solution

For Path identification, users need to:

File: app/Providers/TenancyServiceProvider.php

<?php

namespace App\Providers;

use App\Http\Middleware\SetTenantUrlDefaults;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Livewire\Features\SupportFileUploads\FilePreviewController;
use Livewire\Features\SupportFileUploads\FileUploadController;
use Livewire\Livewire;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;

class TenancyServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Must configure Livewire routes in register() to ensure they take precedence
        $this->configureLivewire();
    }

    public function boot()
    {
        // Remove Livewire's default routes after the application has booted
        // This prevents route name conflicts during php artisan optimize
        $this->app->booted(function () {
            $this->removeLivewireDefaultRoutes();
        });
    }

    protected function configureLivewire(): void
    {
        // 1. Update route - Has official API ✅
        Livewire::setUpdateRoute(function ($handle) {
            return Route::post('/{tenant}/livewire/update', $handle)
                ->middleware([
                    'web',
                    InitializeTenancyByPath::class,
                    SetTenantUrlDefaults::class,
                ]);
        });

        // 2. Upload route - No official API, must manually register ❌
        Route::post('/{tenant}/livewire/upload-file', [FileUploadController::class, 'handle'])
            ->middleware([
                'web',
                InitializeTenancyByPath::class,
                SetTenantUrlDefaults::class,
            ])
            ->name('livewire.upload-file'); // Use same name to override

        // 3. Preview route - No official API, must manually register ❌
        Route::get('/{tenant}/livewire/preview-file/{filename}', [FilePreviewController::class, 'handle'])
            ->middleware([
                'web',
                InitializeTenancyByPath::class,
                SetTenantUrlDefaults::class,
            ])
            ->name('livewire.preview-file'); // Use same name to override
    }

    /**
     * Remove Livewire's default upload and preview routes
     *
     * This prevents route name conflicts when running php artisan optimize
     * by removing the global /livewire/upload-file and /livewire/preview-file routes
     * after we've registered our tenant-specific versions.
     */
    protected function removeLivewireDefaultRoutes(): void
    {
        $router = Route::getFacadeRoot();
        $routes = $router->getRoutes();
        $newRouteCollection = new \Illuminate\Routing\RouteCollection();

        // Filter and re-add routes, excluding Livewire's default routes
        foreach ($routes->getRoutes() as $route) {
            $uri = $route->uri();

            // Skip default upload route (without {tenant} parameter)
            if ($uri === 'livewire/upload-file' && $route->methods()[0] === 'POST') {
                continue;
            }

            // Skip default preview route (without {tenant} parameter)
            if ($uri === 'livewire/preview-file/{filename}' && in_array('GET', $route->methods())) {
                continue;
            }

            // Keep all other routes
            $newRouteCollection->add($route);
        }

        // Replace the route collection with the filtered one
        $router->setRoutes($newRouteCollection);
    }
}

Why This Approach Works:

1. Register tenant routes first (in register()) with the same route names as Livewire's defaults
2. Remove default routes (in booted() callback) after Livewire has registered them
3. This ensures:
  - ✅ Frontend JavaScript finds the correct route names
  - ✅ Route matching works (tenant routes are matched first due to specificity)
  - ✅ php artisan optimize succeeds (no duplicate route names)
  - ✅ File uploads work correctly (proper session isolation)

Verification:

# Check that only tenant routes exist
php artisan route:list --path=livewire

# Expected output:
#   GET|HEAD   {tenant}/livewire/preview-file/{filename}  livewire.preview-file
#   POST       {tenant}/livewire/update                   livewire.update
#   POST       {tenant}/livewire/upload-file              livewire.upload-file

# Verify route caching works
php artisan optimize

# Should succeed without errors ✅

Documentation Request

Please add a Path identification section to the Livewire integration docs:

https://tenancyforlaravel.com/docs/v3/integrations/livewire

Suggested Structure

Livewire Integration

Domain Identification

[Current content...]

Path Identification (NEW)

When using Path identification, you need to customize all Livewire routes to include the {tenant} prefix and remove
Livewire's default routes to prevent conflicts:

Important notes:
- The update route uses the official setUpdateRoute() API
- Upload and preview routes must be manually re-registered
- Route names must match Livewire's defaults (livewire.upload-file, livewire.preview-file)
- Default routes must be removed to prevent route serialization conflicts during php artisan optimize

[Include the complete code example above]

Environment

- Laravel: 12.x
- Livewire: 3.5.x
- stancl/tenancy: 3.9.1
- Tenant identification: Path (InitializeTenancyByPath)

Additional Context

This issue affects all Path identification users who use:
1. Livewire file uploads (419 CSRF errors)
2. Route caching (php artisan optimize failures)

The current workaround requires:
- Understanding both packages' route registration mechanisms
- Knowing about Laravel's route collection manipulation APIs
- Implementing custom route removal logic

Related Discussions

- Users frequently encounter 419 errors with Livewire uploads in multi-tenant setups
- php artisan optimize failures are a common deployment blocker
- The solution requires deep understanding of both packages' internals

Benefits of Adding This Documentation

1. Reduces support burden - Addresses two common issues (CSRF and route caching)
2. Improves DX - Clear migration path from Domain to Path identification
3. Production-ready - Users can deploy with php artisan optimize enabled
4. Completeness - Documentation should cover all identification methods
5. Discoverability - Users can find the solution without digging into source code

Thank you for maintaining this excellent package! 🙏

Steps to reproduce

[Keep existing steps to reproduce...]

Expected behavior

Expected Behavior

When using Path identification with Livewire file uploads:

1. File uploads should work correctly without CSRF errors
2. All Livewire routes should include the tenant prefix:
  - ✅ POST /{tenant}/livewire/update
  - ✅ POST /{tenant}/livewire/upload-file
  - ✅ GET /{tenant}/livewire/preview-file/{filename}
3. Session cookies should have the correct path:
  - Cookie: laravel_session
  - Path: /{tenant} (e.g., /acme)
4. Session isolation should work properly between different tenants
5. Route caching should work:
  - php artisan optimize should succeed without errors
  - No duplicate route name conflicts

Expected Deployment Process

# Build and optimize application
composer install --optimize-autoloader --no-dev
php artisan config:cache
php artisan route:cache  # Should succeed ✅
php artisan view:cache

# Or use the combined command
php artisan optimize  # Should succeed ✅

Expected Network Behavior

When uploading a file from /acme/dashboard:

Request: POST /acme/livewire/upload-file
Response Headers:
  Set-Cookie: laravel_session=...; path=/acme; HttpOnly
Status: 200 OK

Expected User Experience

Users should be able to:
1. Upload files through Livewire components without 419 CSRF errors
2. Deploy applications with route caching enabled
3. Use all Livewire features in Path identification mode
4. Follow clear documentation without reverse-engineering the packages

Laravel version

v12.36.0

stancl/tenancy version

v3.9.1

fdjkgh580 avatar Oct 31 '25 01:10 fdjkgh580

I'm currently facing this same issue and have found that with this approach Livewire doesn't work outside of the tenant context. It's possible to work around that by overriding the Livewire routes when the request matches those that should use tenancy, however this doesn't work alongside route caching.

E.g. if your application has routes like myapp.com/t/{tenant} which uses a tenant but also myapp.com/profile which doesn't then the later won't work with this approach.

HughNoble avatar Nov 10 '25 15:11 HughNoble

The standard approach in v4 is to just use route cloning and the URL generator bootstrapper as we do in the SaaS boilerplate v2 preview. Will have this documented in more detail soon.

stancl avatar Nov 10 '25 15:11 stancl

Oh great. That sounds like a nice solution. I'll keep an eye out for the documentation updates.

HughNoble avatar Nov 10 '25 16:11 HughNoble

https://v4.tenancyforlaravel.com/integrations/livewire/

stancl avatar Nov 11 '25 00:11 stancl