Skip to content

Writing a module ​

A module is a folder that adds one feature: its database tables, API routes, background work, dashboard pages, translations and tests. This walk-through builds a small but complete one, PageViews, that counts the views of each page address per site and shows the most viewed pages on a dashboard page, using the same patterns as the bundled modules (the Events module is the closest model to read next to it).

30 minutesDevelopersSingle user · SaaS

Read Architecture & modules first for the rules: a module never uses another module's classes, only the core's contracts and events.

1. Create the folders ​

text
apps/standalone/modules/PageViews/
├── module.json
├── PageViewsServiceProvider.php
├── Database/Migrations/2026_12_01_000100_create_page_view_counts_table.php
├── Http/Controllers/PageViewsController.php
├── Http/Requests/PageViewsRequest.php
├── Listeners/RecordPageViews.php
├── Listeners/DeleteSitePageViews.php
├── Routes/api.php
├── Resources/js/index.tsx
├── Resources/js/PageViewsPage.tsx
├── Resources/js/locales/de.json …     dashboard texts, one file per language
├── Resources/lang/de.json …           server texts, one file per language
└── Tests/Feature/PageViewsTest.php

The folder name is StudlyCase and becomes the namespace Modules\PageViews. Put modules that only make sense in the SaaS edition into saas/modules/ instead.

2. Describe it in module.json ​

json
{
    "name": "PageViews",
    "version": "1.0.0",
    "requires": { "replora": "^1.0" },
    "description": "The most viewed pages of each site.",
    "provider": "Modules\\PageViews\\PageViewsServiceProvider",
    "enabled": true,
    "abilities": {}
}

The module reuses the recordings:read ability of the Recordings module (a token that may read recordings may read this report). Declare your own abilities in abilities when the module needs them.

3. Write the service provider ​

php
<?php

namespace Modules\PageViews;

use App\Events\Recordings\BatchStored;
use App\Events\Recordings\SiteDeleted;
use App\Modules\ModuleServiceProvider;
use Illuminate\Support\Facades\Event;
use Modules\PageViews\Listeners\DeleteSitePageViews;
use Modules\PageViews\Listeners\RecordPageViews;

/**
 * Registers the PageViews module: counts the page views of every stored batch, serves its API and cleans up when a
 * site is deleted.
 */
class PageViewsServiceProvider extends ModuleServiceProvider
{
    /**
     * Folder name of this module.
     */
    protected function moduleName(): string
    {
        return 'PageViews';
    }

    /**
     * Routes, migrations and translations (parent), then the listeners.
     */
    public function boot(): void
    {
        parent::boot();
        Event::listen(BatchStored::class, RecordPageViews::class);
        Event::listen(SiteDeleted::class, DeleteSitePageViews::class);
    }
}

parent::boot() loads Routes/api.php under /api/v1, Database/Migrations, Resources/lang and Resources/views; parent::register() merges Config/pageviews.php if you add one.

4. Add a migration ​

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Page views: one row per view, with the session and the page address.
 */
return new class extends Migration
{
    /**
     * Creates the table.
     */
    public function up(): void
    {
        Schema::create('page_view_counts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('site_id');
            $table->uuid('session');
            $table->string('url', 2048);
            $table->bigInteger('at_ms');
            $table->index(['site_id', 'at_ms']);
        });
    }

    /**
     * Drops it.
     */
    public function down(): void
    {
        Schema::dropIfExists('page_view_counts');
    }
};

Use your own table names (prefixed with the module's name) and plain ids: no foreign keys to another module's tables.

5. Build data from recorded sessions ​

BatchStored is fired after each stored batch with plain values: the site, the session, its visitor facts, every page view so far (pageviews), the page views this batch added (newPageviews, each ['url' => …, 'at_ms' => …]) and the tracker's custom events (signals). This module keeps the new page views.

php
<?php

namespace Modules\PageViews\Listeners;

use App\Events\Recordings\BatchStored;
use Illuminate\Support\Facades\DB;

/**
 * Keeps the page views a stored batch added.
 */
class RecordPageViews
{
    /**
     * Inserts one row per new page view.
     */
    public function handle(BatchStored $event): void
    {
        $rows = array_map(fn (array $view): array => [
            'site_id' => $event->siteId,
            'session' => $event->sessionUuid,
            'url' => mb_substr($view['url'], 0, 2048),
            'at_ms' => $view['at_ms'],
        ], $event->newPageviews);
        if ($rows !== []) {
            DB::table('page_view_counts')->insert($rows);
        }
    }
}

Check what the payload holds

App\Events\Recordings\BatchStored documents every field. Custom events in signals (click, rage, error, event, form…) are described in packages/tracker/src/signals.ts and forms.ts. Every value comes from a visitor's browser, so check and shorten it before storing.

DeleteSitePageViews listens to SiteDeleted and deletes the site's rows (DB::table('page_view_counts')->where('site_id', $event->siteId)->delete()).

6. Add API routes ​

php
<?php

use Illuminate\Support\Facades\Route;
use Modules\PageViews\Http\Controllers\PageViewsController;

/*
| The most viewed pages of a site under /api/v1 (session or token with recordings:read).
*/

Route::middleware(['auth:sanctum', 'abilities:recordings:read'])->prefix('sites/{site}/pageviews')->whereNumber('site')->name('pageviews.')->group(function (): void {
    Route::get('/', [PageViewsController::class, 'index'])->name('index');
});

The api group adds rate limiting, roles (viewers can only read), suspended-account checks and the person's language. Check access to the site through the core's SiteDirectory contract, never through the Recordings module:

php
<?php

namespace Modules\PageViews\Http\Requests;

use App\Contracts\Sites\SiteDirectory;
use Illuminate\Foundation\Http\FormRequest;

/**
 * Reading a site's page views: members of the site's account only (others get the same 404 as a missing site).
 */
class PageViewsRequest extends FormRequest
{
    /**
     * Members of the site's account only.
     */
    public function authorize(): bool
    {
        abort_unless(app(SiteDirectory::class)->visibleTo((int) $this->route('site'), $this->user()), 404);

        return true;
    }

    /**
     * Query rules.
     *
     * @return array<string, array<int, string>>
     */
    public function rules(): array
    {
        return ['days' => ['sometimes', 'integer', 'in:7,30,90']];
    }
}
php
<?php

namespace Modules\PageViews\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Modules\PageViews\Http\Requests\PageViewsRequest;

/**
 * A site's page views per address.
 */
class PageViewsController extends Controller
{
    /**
     * The 100 most viewed addresses of the period.
     */
    public function index(PageViewsRequest $request, int $site): JsonResponse
    {
        $from = now()->subDays((int) ($request->validated('days') ?? 30))->getTimestampMs();
        $rows = DB::table('page_view_counts')->where('site_id', $site)->where('at_ms', '>=', $from)
            ->groupBy('url')->select('url')->selectRaw('COUNT(*) AS views, COUNT(DISTINCT session) AS sessions')
            ->orderByDesc('views')->limit(100)->get();

        return response()->json(['data' => $rows]);
    }
}

Errors follow the API's one shape automatically ({"message": …}, errors for 422). Document new endpoints in the repository's docs/openapi.yaml: a test keeps it complete, and the API reference of these docs is generated from it.

7. Add a dashboard page ​

Resources/js/index.tsx registers what the module adds to the dashboard:

tsx
import { lazy, Suspense } from 'react';
import { defineModule } from '@app/lib/extensions';
import { registerCatalogs } from '@app/lib/i18n';
import { PageLoading } from '@app/layout/PageLoading';

const PageViewsPage = lazy(() => import('./PageViewsPage').then((m) => ({ default: m.PageViewsPage })));

// This module's interface texts in other languages (locales/<lang>.json).
registerCatalogs(import.meta.glob('./locales/*.json'));

/** Dashboard part of the PageViews module: /sites/:id/pageviews, linked from each site's pages. */
export default defineModule({
  name: 'PageViews',
  siteLinks: (siteId) => [{ label: 'Page views', icon: 'activity', href: `/sites/${siteId}/pageviews` }],
  page(path) {
    const m = path.match(/^\/sites\/(\d+)\/pageviews$/);
    return m ? <Suspense fallback={<PageLoading />}><PageViewsPage siteId={m[1]!} /></Suspense> : null;
  },
});
tsx
import { useEffect, useState } from 'react';
import { Card, Spinner, t } from '@replora/ui';
import { Dashboard } from '@app/layout/Dashboard';
import { PageHead } from '@app/layout/PageHead';
import { api } from '@app/lib/api';

interface Row { url: string; views: number; sessions: number }

/** The most viewed pages, most viewed first. */
export function PageViewsPage({ siteId }: { siteId: string }) {
  const [rows, setRows] = useState<Row[] | null>(null);
  useEffect(() => { api<{ data: Row[] }>('GET', `sites/${siteId}/pageviews`).then((r) => setRows(r.data)); }, [siteId]);

  return (
    <Dashboard crumbs={[{ label: 'Sites', href: '/sites' }, { label: 'Page views' }]}>
      <PageHead eyebrow={t('Page views')} title={t('Most viewed pages')} />
      <Card>
        {rows === null ? <Spinner /> : (
          <table className="ml-table">
            <thead><tr><th>{t('Page')}</th><th>{t('Views')}</th><th>{t('Sessions')}</th></tr></thead>
            <tbody>{rows.map((r) => <tr key={r.url}><td>{r.url}</td><td>{r.views}</td><td>{r.sessions}</td></tr>)}</tbody>
          </table>
        )}
      </Card>
    </Dashboard>
  );
}

Use the shared UI kit (@replora/ui) and the dashboard's layout so the page looks like the rest. Other extension points (sidebar entries, replay tabs, settings cards, the session-list toolbar…) are listed in Dashboard extensions.

8. Translate the texts ​

  • Dashboard: every text goes through t('…'). node tools/check-i18n.mjs --write (or pnpm i18n:write) adds the missing keys, empty, to Resources/js/locales/<lang>.json for every language; fill them in.
  • Server: messages in PHP go through __('…'), translated in Resources/lang/<lang>.json.

pnpm i18n fails while a text is missing or empty in any language, or while a visible string in JSX isn't wrapped in t(). The languages are en, es, fr, de, pt, it, ru, zh, ja, ko, tr, id, ar (English is the key itself).

9. Write tests ​

PHP tests live in the module (Tests/Feature/*Test.php) and run with the whole suite (phpunit.xml includes modules/* and saas/modules/*). Replace the SiteDirectory contract so the test needs no Recordings module:

php
<?php

namespace Modules\PageViews\Tests\Feature;

use App\Contracts\Sites\SiteDirectory;
use App\Events\Recordings\BatchStored;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

/**
 * Page views: kept from stored batches and listed per address for members of the site's account.
 */
class PageViewsTest extends TestCase
{
    use RefreshDatabase;

    /**
     * A stored page view is counted for the site's members only.
     */
    public function test_page_views_are_counted(): void
    {
        $owner = User::factory()->create();
        $this->app->instance(SiteDirectory::class, new class($owner->id) implements SiteDirectory
        {
            public function __construct(private int $ownerId) {}

            public function visibleTo(int $siteId, User $user): bool
            {
                return $siteId === 7 && $user->id === $this->ownerId;
            }

            public function name(int $siteId): ?string
            {
                return null;
            }
        });

        $view = ['url' => 'https://shop.example/pricing', 'at_ms' => now()->getTimestampMs()];
        event(new BatchStored(7, '0b6f0a3e-1c2d-4e5f-8a9b-0c1d2e3f4a5b', [], [$view], [$view], true, []));

        Sanctum::actingAs($owner);
        $this->getJson('/api/v1/sites/7/pageviews')->assertOk()->assertJsonPath('data.0.url', 'https://shop.example/pricing');
        $this->getJson('/api/v1/sites/8/pageviews')->assertNotFound();
    }
}

Front-end logic in plain .ts files next to the page gets Vitest tests (*.test.ts); pnpm test:coverage requires 100 % for modules/*/Resources/js/*.ts. Then run the whole gate: composer check (module independence, PHPDoc on every class and public method, Pint, PHPUnit with 100 % line coverage).

10. Turn it on ​

sh
cd apps/standalone
php artisan migrate          # the module's tables
cd ../.. && pnpm build       # the dashboard bundle with the new page
php artisan optimize:clear   # if you cache routes or config (run in apps/standalone)

The module runs as soon as its folder is there and "enabled": true. GET /api/v1/app lists it under modules. To switch it off, set "enabled": false: its routes, pages and listeners stop at once, its data stays. To remove it, delete the folder and rebuild.

Plan limits and settings

To make the feature a plan option in the SaaS edition, tag a UsageSource with a feature key (pageviews.enabled), protect the routes with plan:pageviews.enabled and hide the page with planAllows('pageviews.enabled'). To let administrators change a setting in the dashboard, tag a SettingsSource. Health checks, personal-data export and overview numbers work the same way; see Contracts.

Releases

Bundled modules are listed in apps/standalone/resources/core-pack.json so the signed module pack carries them; pnpm release fails while a module in modules/ is missing from that list. See Releases & module packs.

Replora: see what your visitors see.