# Multi-tenant apps

Session Replay works with any way of keeping workspaces apart: Filament's own tenancy, [stancl/tenancy](https://tenancyforlaravel.com) with one database or one per tenant, [spatie/laravel-multitenancy](https://github.com/spatie/laravel-multitenancy), or a team column of your own. Every setup on this page runs end to end, with the viewer, a Filament panel, a central console and [Assist](https://packstub.dev/docs/session-replay/assist), on a local disk and on S3, in [packstub/session-replay-tenancy-demo](https://github.com/packstub/session-replay-tenancy-demo).

## Three things every setup needs

1. **The workspace in each recording.** `SessionReplay::tenantUsing()` names it when the page renders, and the recorder's signed token carries it to the upload, which therefore needs no tenancy of its own. Return the tenant model itself, not its id (a bare id is dropped). In a Filament panel with tenancy, the panel's tenant is used.

   ```php
   use Packstub\SessionReplay\Facades\SessionReplay;

   SessionReplay::tenantUsing(fn ($request) => tenant()); // stancl; Tenant::current() with spatie
   ```

2. **The workspace checked in the gate and in the list.** `visibleUsing()` keeps other workspaces' rows out of a list; the `viewSessionReplay` gate decides about each recording, its player and its files. The list rule alone is not enough: the player's data routes ask only the gate.

3. **Rules that hold wherever they are asked.** The gate is asked on the viewer's pages, on the player's data routes, and by Assist from the visitor's own requests (to check the agent may still help). Compare the recording with **the person** when you can (their team, their `tenant_id`): such a rule needs no tenant to be initialised. A rule that reads the current tenant (`tenant()`, `Tenant::current()`) needs tenancy on every one of those routes.

## At a glance

| | Tables | Disk | `ingest.middleware` (uploads, Assist's visitor) | `viewer.middleware` | The gate compares the recording with |
| --- | --- | --- | --- | --- | --- |
| Filament's own tenancy | as they are | as it is | nothing | as it is | the person's teams |
| stancl/tenancy, one database | as they are | [its own](#a-disk-of-its-own) | nothing | tenancy before `auth` | the person's `tenant_id` |
| stancl/tenancy, a database per tenant | [central](#tables-on-the-central-connection) | [its own](#a-disk-of-its-own) | tenancy, for Assist | tenancy before `auth` | `tenant()` |
| spatie/laravel-multitenancy, a database per tenant | [central](#tables-on-the-central-connection) | as it is | nothing | as it is | `Tenant::current()` |

## Tables on the central connection

With a database per tenant, keep the replay tables on the central connection, so operators see every workspace in one place and no tenant database grows with recordings:

```dotenv
SESSION_REPLAY_DB_CONNECTION=central
```

```php
// config/session-replay.php
'storage' => ['connection' => env('SESSION_REPLAY_DB_CONNECTION')],
'run_migrations' => false,
```

With `run_migrations` off, publish the migrations and run them where your central migrations live (`php artisan vendor:publish --tag=session-replay-migrations`). The models and the migrations both follow `storage.connection`. For Assist, set `holler.connection` (`HOLLER_DB_CONNECTION`) to the same connection.

The people stay where they are: the recorded user, the workspace and the impersonator load on their model's own connection, or on the default one when the model declares none, so a user in a tenant's database is found once that tenant is initialised. Where a person cannot be reached at all (a central console, with no tenant initialised), the viewer shows them by key, or by your own label ([A central console](#a-central-console)).

## A disk of its own

Recordings are uploaded in one request and played back in another. A tenancy package that moves a disk's root per tenant writes them in one place and looks for them in another, and the player gets a 404 for every chunk. stancl/tenancy does that to every disk in `tenancy.filesystem.disks` (`local` and `public` by default, `s3` once you add it), so give the recordings a disk that is not on that list:

```php
// config/filesystems.php
'session-replay' => [
    'driver' => 'local',
    'root' => storage_path('app/private'), // your `local` disk's root, so recordings made so far keep playing
    'throw' => false,
],
```

```dotenv
SESSION_REPLAY_DISK=session-replay
```

On S3 or R2, copy your `s3` entry under a new name (same bucket and keys) and point `SESSION_REPLAY_DISK` at it. Run `php artisan config:clear` after the change. spatie/laravel-multitenancy and Filament's own tenancy move no disk.

## stancl/tenancy

**The viewer.** Run tenancy before `auth`, so the support person signs in to their own tenant's users:

```php
// config/session-replay.php
'viewer' => ['middleware' => ['web', InitializeTenancyByDomain::class, PreventAccessFromCentralDomains::class, 'auth']],
```

`PreventAccessFromCentralDomains` answers the viewer on your central domain with a 404 instead of stancl's "tenant could not be identified" error. On stancl 4 it is `PreventAccessFromUnwantedDomains`, with `ScopeSessions` after it as on your other tenant routes. For a central console as well, make the routes universal instead ([A central console](#a-central-console)).

**A database per tenant.** The rules read the current tenant:

```php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Gate;
use Packstub\SessionReplay\Models\ReplaySession;

Gate::define('viewSessionReplay', function ($user, ?ReplaySession $session = null): bool {
    $tenant = tenant();

    if ($tenant === null || ! $user->is_support) { // is_support: your own rule
        return false;
    }

    // No recording: the gate is asked for the list itself, which visibleUsing() below scopes to the tenant.
    return $session === null
        || ($session->tenant_type === $tenant->getMorphClass() && $session->tenant_id === (string) $tenant->getKey());
});

SessionReplay::visibleUsing(function (Builder $query): void {
    $query->where('tenant_type', tenant()->getMorphClass())->where('tenant_id', (string) tenant()->getKey());
});
```

Without the workspace in the gate, a recording of another tenant would show the person of this tenant who has the same id. With [Assist](https://packstub.dev/docs/session-replay/assist), the call is started in the visitor's request and the agent is loaded there, from the tenant's database; its visitor routes share `ingest.middleware`, so initialise tenancy there too, and register `Holler::routes()` inside your tenant routes:

```php
'ingest' => ['middleware' => [InitializeTenancyByDomain::class]],
```

**One database.** The people carry their tenant (`BelongsToTenant`, a `tenant_id` column), so the rules compare the recording with the person and hold in any request, Assist's included, with nothing on `ingest.middleware`:

```php
Gate::define('viewSessionReplay', fn ($user, ?ReplaySession $session = null): bool => $user->is_support
    && ($session === null || ($session->tenant_type === (new Tenant)->getMorphClass() && $session->tenant_id === (string) $user->tenant_id)));

SessionReplay::visibleUsing(fn (Builder $query, $viewer) => $query
    ->where('tenant_type', (new Tenant)->getMorphClass())->where('tenant_id', (string) $viewer?->tenant_id));
```

**In a Filament panel** on the tenant's domain, add the tenancy middleware to the panel as persistent middleware (`->middleware([InitializeTenancyByDomain::class, ...], isPersistent: true)`), with Filament Session Replay 1.2.1 or later: it records the panel's pages with `tenantUsing()`'s workspace when the panel has no Filament tenant of its own.

## spatie/laravel-multitenancy

spatie finds the current tenant on every request, the upload and Assist's visitor routes included, and moves no disk: register `tenantUsing(fn () => Tenant::current())`, the rules of the stancl example with `Tenant::current()` in place of `tenant()`, and the central connection for the tables. Nothing goes on `ingest.middleware` or `viewer.middleware`. In a Filament panel, `NeedsTenant` can be persistent middleware, but `EnsureValidTenantSession` reads the session, so it goes in the panel's own middleware after `StartSession`.

## Filament's own tenancy

The panel's tenant is in every recording made in it, and the Sessions resource lists the current tenant's recordings ([Filament Session Replay's tenancy guide](https://github.com/packstub/filament-session-replay/blob/main/docs/tenancy.md)). The gate still guards the core's data routes, outside the panel, so compare the recording with the person's teams there:

```php
Gate::define('viewSessionReplay', fn ($user, ?ReplaySession $session = null): bool => $user->is_support
    && ($session === null || ($session->tenant_type === (new Team)->getMorphClass()
        && $user->teams()->whereKey($session->tenant_id)->exists())));
```

## A central console

Operators who watch every workspace from the central domain (an operator panel, the core's viewer there) need the player's data routes to work without a tenant, and the gate to let them through:

- **Routes that work with and without a tenant.** With stancl, make `viewer.middleware` universal: `['web', 'universal', InitializeTenancyByDomain::class, 'auth:web,operator']` (on stancl 3, turn on `Stancl\Tenancy\Features\UniversalRoutes` and register an empty `universal` middleware group; stancl 4 has both built in). spatie needs nothing: it initialises no tenant on the central domain.
- **The operators' guard.** `auth:web,operator` lets either sign in; the gate is handed whoever did. Give the operators a model and guard of their own, on the central connection.
- **The gate**, let them through first: `if ($user instanceof Operator) return true;`, and `visibleUsing()` leaves their query alone.
- **The people's names.** With a database per tenant, the people are not on the central connection, so the viewer shows them by key (Session Replay 1.4.0 or later; earlier versions fail the page) unless you name them, for example by looking each one up in their tenant. For the built-in viewer and Assist's pages (Session Replay 1.4.0 or later):

  ```php
  SessionReplay::userLabelUsing(fn (ReplaySession $session): ?string => $session->user_id === null ? null
      : $session->tenant?->run(fn () => User::find($session->user_id)?->email)); // execute() with spatie
  ```

  In a Filament panel, give the same closure to the plugin: `SessionReplayPlugin::make()->userLabelUsing(...)`.
