Skip to main content
CakeDC Blog

Reactive CakePHP views with Datastar

Cover photo: "speed" by Andrew Fogg, licensed under CC BY 2.0.

Today we're going to add some reactivity to a CakePHP application without writing a single line of JavaScript, using Datastar. We'll build a contacts page with a live search, a form that shows validation errors inline, a delete button, and a long-running job that streams its progress to the browser while it works.

If you've been following the blog, you may remember the htmx series (Building Dynamic Web Applications with CakePHP and HTMX). Datastar plays in the same field: the server renders HTML, the browser swaps it in. The difference is that Datastar also ships a small reactive state layer in the browser, and it speaks Server-Sent Events natively, so a button click and a streaming progress bar use exactly the same mechanism.

The example app uses CakePHP 5.4, PHP 8.5 and Postgres, running under DDEV, and it's available at CakeDC/cakephp-datastar-example. Clone it, run ddev start and you're ready to play with it.

1. What is Datastar?

Datastar is a single JavaScript module (about 14 KB gzipped) that you drive with data-* attributes. It gives you two things:

  • Signals: reactive variables declared in your markup, similar to what Alpine.js does.
  • Backend actions: @get(), @post(), @put(), @patch() and @delete() send a request to your server and apply whatever comes back.

The important idea is that the server is the source of truth. Your controller decides what the page looks like and sends HTML; Datastar morphs it into the DOM, matching elements by id and touching only what changed. No client side state management, and no JSON API whose only purpose is to be converted back into HTML.

A quick look at signals:

<div data-signals="{count: 0}">
    <button data-on:click="$count++">+1</button>
    <span data-text="$count"></span>
</div>

The attributes we'll use in this article are data-signals, data-bind:name (two way binding with an input), data-text, data-attr:disabled, data-class:something, data-on:click (with modifiers like __debounce.300ms or __prevent) and data-indicator:loading, which sets $loading to true while a request from that element is in flight.

Note: Datastar 1.0 uses the colon syntax (data-on:click). You'll find older examples online using dashes (data-on-click), those were renamed before the 1.0 release.

Every backend action sends all the signals to the server automatically. For GET they go in a datastar query parameter (JSON encoded), for everything else as a JSON body. The request also carries a Datastar-Request: true header. Signals starting with an underscore ($_local) stay in the browser.

And the server can answer with:

  • text/html: a fragment, morphed into the element with the same id. The simplest option.
  • text/event-stream: Server-Sent Events. This is the native format, and the only one that can push several updates over a single open connection.
  • application/json (merged into the signals) or text/javascript (executed), less common.

There are only two SSE events you need to know about:

event: datastar-patch-elements
data: selector #job-log
data: mode append
data: elements <li>Processed Ada Lovelace</li>

event: datastar-patch-signals
data: signals {"progress": 13}

datastar-patch-elements accepts an optional selector and a mode (outer is the default and morphs by id; there are also inner, replace, prepend, append, before, after and remove). datastar-patch-signals merges the values into the signals, setting one to null removes it. Each event ends with a blank line.

2. Loading Datastar

Add the module to templates/layout/default.php:

<?= $this->Html->script(
    'https://cdn.jsdelivr.net/gh/starfederation/[email protected]/bundles/datastar.js',
    ['type' => 'module']
) ?>
<?= $this->fetch('script') ?>

Pin the version. In production you'll probably want to copy the file into webroot/js/ and load it from there.

3. A Datastar component

For the example project, we don't need any dependency. We'll create a small component to read the signals from the request and to build the SSE responses, that's src/Controller/Component/DatastarComponent.php:

<?php
declare(strict_types=1);

namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Http\CallbackStream;
use Cake\Http\Response;

class DatastarComponent extends Component
{
    public function isDatastar(): bool
    {
        return $this->getController()->getRequest()->getHeaderLine('Datastar-Request') === 'true';
    }

    public function signals(): array
    {
        $request = $this->getController()->getRequest();
        if ($request->is('get')) {
            $raw = (string)$request->getQuery('datastar', '');
            $decoded = $raw === '' ? [] : json_decode($raw, true);

            return is_array($decoded) ? $decoded : [];
        }

        // JSON body, already parsed by BodyParserMiddleware
        $data = $request->getData();

        return is_array($data) ? $data : [];
    }

    public function element(string $name, array $data = []): string
    {
        return $this->getController()->createView()->element($name, $data);
    }

    public function patchElements(string $html, array $options = []): string
    {
        $lines = [];
        if (isset($options['selector'])) {
            $lines[] = 'selector ' . $options['selector'];
        }
        if (isset($options['mode'])) {
            $lines[] = 'mode ' . $options['mode'];
        }
        if (!empty($options['useViewTransition'])) {
            $lines[] = 'useViewTransition true';
        }
        $html = trim($html);
        if ($html !== '') {
            foreach (preg_split('/\r\n|\r|\n/', $html) ?: [] as $line) {
                $lines[] = 'elements ' . $line;
            }
        }

        return $this->event('datastar-patch-elements', $lines);
    }

    public function patchSignals(array $signals, bool $onlyIfMissing = false): string
    {
        $lines = [];
        if ($onlyIfMissing) {
            $lines[] = 'onlyIfMissing true';
        }
        $lines[] = 'signals ' . json_encode($signals, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);

        return $this->event('datastar-patch-signals', $lines);
    }

    public function respond(string ...$events): Response
    {
        return $this->sseResponse()->withStringBody(implode('', $events));
    }

    public function stream(callable $producer): Response
    {
        // release the session lock, or every other request from this user
        // will wait until the stream is finished
        $this->getController()->getRequest()->getSession()->close();

        $body = new CallbackStream(function () use ($producer): void {
            while (ob_get_level() > 0) {
                ob_end_flush();
            }
            $send = function (string $event): void {
                echo $event;
                flush();
            };
            $producer($send);
        });

        return $this->sseResponse()->withBody($body);
    }

    protected function event(string $type, array $dataLines): string
    {
        $out = "event: {$type}\n";
        foreach ($dataLines as $line) {
            $out .= "data: {$line}\n";
        }

        return $out . "\n";
    }

    protected function sseResponse(): Response
    {
        return $this->getController()->getResponse()
            ->withType('text/event-stream')
            ->withHeader('Cache-Control', 'no-cache')
            ->withHeader('X-Accel-Buffering', 'no'); // don't let nginx buffer the stream
    }
}

Two things to note:

  • patchElements() and patchSignals() only format the events as strings. respond() joins them into a regular PSR-7 response, so it goes through the middleware stack as usual and you can assert it in your integration tests like any other response.
  • stream() uses CakePHP's own CallbackStream. The response emitter calls the callback when sending the body, so we can echo and flush() each event as soon as it's ready. No exit(), no headers sent behind the framework's back.

There is an official PHP SDK, starfederation/datastar-php, and it's fine for plain PHP. But its ServerSentEventGenerator sends the headers and echoes the output by itself, bypassing the CakePHP response. For a CakePHP app these ~100 lines fit better.

Load it in your controller, or in AppController if you plan to use it everywhere:

$this->loadComponent('Datastar');

Why a component and not a middleware? For this article we decided to keep everything related to Datastar in one place, so it's easier to follow. In a real app, or if you're packaging this as a plugin, it would make sense to move the request side to a middleware: decode the signals once and store them as a request attribute, flag Datastar requests so you can check $this->request->is('datastar'), and, more importantly, catch errors. A component can't help when the request fails before reaching the controller (an expired CSRF token, for example), and right now that means the user clicks and nothing happens. A middleware can turn those errors into a datastar-patch-elements event with a proper message. Building the responses (patchElements(), respond(), stream()) would stay in the component, since it needs the view and the action's own logic.

4. A helper for the actions (and CSRF)

CsrfProtectionMiddleware will reject any POST, PUT, PATCH or DELETE without a valid token, and Datastar requests are not an exception. The middleware accepts the token in a X-CSRF-Token header, and Datastar actions accept a headers option, so we just need to connect both. While we're at it, we'll use routing arrays instead of hardcoded URLs. That's src/View/Helper/DatastarHelper.php:

<?php
declare(strict_types=1);

namespace App\View\Helper;

use Cake\Routing\Router;
use Cake\View\Helper;

class DatastarHelper extends Helper
{
    public function get(array|string $url): string    { return $this->action('get', $url); }
    public function post(array|string $url): string   { return $this->action('post', $url); }
    public function put(array|string $url): string    { return $this->action('put', $url); }
    public function patch(array|string $url): string  { return $this->action('patch', $url); }
    public function delete(array|string $url): string { return $this->action('delete', $url); }

    protected function action(string $method, array|string $url): string
    {
        $flags = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES;
        $expr = sprintf('@%s(%s', $method, json_encode(Router::url($url), $flags));
        if ($method !== 'get') {
            $token = (string)$this->getView()->getRequest()->getAttribute('csrfToken');
            $expr .= sprintf(', {headers: {"X-CSRF-Token": %s}}', json_encode($token, $flags));
        }

        // already escaped, ready to be used inside an attribute
        return h($expr . ')');
    }
}

$this->Datastar->post(['action' => 'add']) renders @post("/contacts/add", {headers: {"X-CSRF-Token": "..."}}). Register it in src/View/AppView.php:

public function initialize(): void
{
    $this->addHelper('Datastar');
}

The app skeleton already includes BodyParserMiddleware, so the JSON body sent by Datastar is available in $this->request->getData() without any extra configuration.

5. The page

All the client state is declared once at the top of templates/Contacts/index.php, and the rest is regular markup:

<div data-signals="{q: '', name: '', email: '', errors: {name: '', email: ''}, progress: 0}">
    <h1>Contacts</h1>

    <input type="search" placeholder="Search by name or email…"
           data-bind:q
           data-indicator:searching
           data-on:input__debounce.300ms="<?= $this->Datastar->get(['action' => 'search']) ?>">

    <div class="results" data-class:is-searching="$searching">
        <?= $this->element('Contacts/list', compact('contacts')) ?>
    </div>

    <h2>Add a contact</h2>
    <form data-on:submit__prevent="<?= $this->Datastar->post(['action' => 'add']) ?>"
          data-indicator:saving>
        <label>Name <input type="text" data-bind:name></label>
        <small class="error" data-text="$errors.name"></small>

        <label>Email <input type="text" data-bind:email></label>
        <small class="error" data-text="$errors.email"></small>

        <button type="submit" data-attr:disabled="$saving">Add</button>
    </form>

    <h2>A long-running job</h2>
    <button data-on:click="<?= $this->Datastar->post(['action' => 'recalculate']) ?>"
            data-indicator:working
            data-attr:disabled="$working">
        Recalculate everything
    </button>
    <progress max="100" data-attr:value="$progress"></progress>
    <span data-text="$progress + '%'"></span>
    <ol id="job-log"></ol>
    <p id="job-status"></p>
</div>

The list is a regular element, templates/element/Contacts/list.php. The stable id attributes are what makes the morphing work:

<ul id="contact-list">
    <?php foreach ($contacts as $contact): ?>
        <li id="contact-<?= $contact->id ?>">
            <strong><?= h($contact->name) ?></strong> &lt;<?= h($contact->email) ?>&gt;
            <button class="button-clear"
                    data-on:click="<?= $this->Datastar->delete(['action' => 'delete', $contact->id]) ?>">
                delete
            </button>
        </li>
    <?php endforeach; ?>
    <?php if ($contacts->count() === 0): ?>
        <li id="contact-empty"><em>No contacts match.</em></li>
    <?php endif; ?>
</ul>

The same element renders the full page and every partial update, so your templates don't split into a "page version" and an "ajax version".

A note about the loading indicator. My first version had a <p data-show="$searching">Searching…</p> under the input. The search takes a few milliseconds, so the message was appearing and disappearing on every keystroke, and since data-show toggles display, the list was jumping too. That's flickering, not feedback. The fix is to let data-indicator drive a class, and let CSS wait until the request is actually slow:

<?php $this->append('css', '<style>
    .results #contact-list { transition: opacity .15s; }
    /* only dim if the search takes longer than 200ms */
    .results.is-searching #contact-list { opacity: .5; transition-delay: .2s; }
</style>'); ?>

Fast responses show nothing, slow ones dim the results, and opacity doesn't change the layout. The class goes on a wrapper <div> and not on #contact-list itself because the server replaces #contact-list, and the morph would remove a data-class the server HTML doesn't have.

6. The controller

index() is a regular action, nothing special there. Let's go through the other four.

Live search, plain HTML

public function search(): ?Response
{
    $term = (string)($this->Datastar->signals()['q'] ?? '');
    $contacts = $this->Contacts->find('search', term: $term)->all();
    $this->set(compact('contacts'));
    $this->viewBuilder()->disableAutoLayout();

    return $this->render('/element/Contacts/list');
}

That's the whole integration for the search. Datastar sends ?datastar={"q":"gra"}, we render the element without layout as a normal text/html response, and Datastar morphs <ul id="contact-list"> into the page. No SSE involved.

The finder is regular ORM code. If you're on Postgres, keep in mind LIKE is case sensitive there, so we lowercase both sides:

public function findSearch(SelectQuery $query, string $term = ''): SelectQuery
{
    $term = trim($term);
    if ($term !== '') {
        $like = '%' . mb_strtolower(addcslashes($term, '%_\\')) . '%';
        $query->where(fn (QueryExpression $exp, SelectQuery $q) => $exp->or([
            $exp->like($q->func()->lower(['Contacts.name' => 'identifier']), $like),
            $exp->like($q->func()->lower(['Contacts.email' => 'identifier']), $like),
        ]));
    }

    return $query->orderBy(['Contacts.name' => 'ASC'])->limit(50);
}

Add, several updates in one response

public function add(): Response
{
    $this->request->allowMethod('post');
    $signals = $this->Datastar->signals();

    $contact = $this->Contacts->newEntity([
        'name' => $signals['name'] ?? '',
        'email' => $signals['email'] ?? '',
    ]);
    $saved = $this->Contacts->save($contact) !== false;

    $errors = [];
    foreach (['name', 'email'] as $field) {
        $errors[$field] = implode(' ', $contact->getError($field));
    }

    if (!$saved) {
        return $this->Datastar->respond($this->Datastar->patchSignals(['errors' => $errors]));
    }

    $contacts = $this->Contacts->find('search', term: (string)($signals['q'] ?? ''))->all();

    return $this->Datastar->respond(
        $this->Datastar->patchElements($this->Datastar->element('Contacts/list', compact('contacts'))),
        $this->Datastar->patchSignals(['name' => '', 'email' => '', 'errors' => $errors]),
    );
}

This is where SSE is useful even without streaming:

  • Validation stays in the Table class. getError() feeds the $errors signal, and data-text="$errors.name" shows it next to the field. Nothing is duplicated in JavaScript.
  • We send the errors for every field, using an empty string for the valid ones. Signal patches are merged, so if we skipped a field it would keep showing the old error.
  • When the contact is saved, a single response refreshes the list (using the current search, $q came with the other signals) and resets the form.

Important: build the entity with the fields you expect, don't pass the whole signals array to newEntity(). Your $_accessible rules still apply, but there's no reason to rely only on them.

Delete, targeting an element

public function delete(int $id): Response
{
    $this->request->allowMethod('delete');
    $this->Contacts->delete($this->Contacts->get($id));

    return $this->Datastar->respond(
        $this->Datastar->patchElements('', ['selector' => '#contact-' . $id, 'mode' => 'remove']),
    );
}

A long-running job, streaming

public function recalculate(): Response
{
    $this->request->allowMethod('post');
    $contacts = $this->Contacts->find()->all()->toList();
    $total = count($contacts);

    return $this->Datastar->stream(function (callable $send) use ($contacts, $total): void {
        // reset the UI from a previous run
        $send($this->Datastar->patchSignals(['progress' => 0]));
        $send($this->Datastar->patchElements('<ol id="job-log"></ol>'));
        $send($this->Datastar->patchElements('<p id="job-status"></p>'));

        foreach ($contacts as $i => $contact) {
            usleep(400_000); // pretend this is expensive
            $send($this->Datastar->patchSignals(['progress' => (int)round(($i + 1) / $total * 100)]));
            $send($this->Datastar->patchElements(
                '<li>Processed ' . h($contact->name) . '</li>',
                ['selector' => '#job-log', 'mode' => 'append'],
            ));
        }
        $send($this->Datastar->patchElements('<p id="job-status">Done: ' . $total . ' contacts.</p>'));
    });
}

The request stays open while the loop runs, and every $send() reaches the browser immediately: the progress bar moves, a new line is appended to the log, and when the response ends $working goes back to false and the button is enabled again. You can see it with curl (timestamps added) through DDEV's nginx-fpm:

$ curl -skN -X POST ... https://datastar-cakephp-example.ddev.site/contacts/recalculate
53.24 data: signals {"progress":0}
53.64 data: signals {"progress":13}
54.05 data: signals {"progress":25}
...
56.45 data: signals {"progress":100}

One event every ~400ms, not everything at the end. Remember to escape anything coming from users when you build HTML strings by hand (h($contact->name) above), and if it's more than one line, render an element instead.

7. How do we test it?

The responses are regular PSR-7 responses, so a standard integration test works:

public function testAddShowsValidationErrors(): void
{
    $this->enableCsrfToken();
    $this->configRequest(['headers' => ['Datastar-Request' => 'true']]);
    $this->post('/contacts/add', ['name' => '', 'email' => 'bad']);

    $this->assertResponseOk();
    $this->assertContentType('text/event-stream');
    $this->assertResponseContains('event: datastar-patch-signals');
    $this->assertResponseContains('Name is required.');
}

public function testSearchReturnsFragment(): void
{
    $this->get('/contacts/search?datastar=' . urlencode('{"q":"ADA"}'));

    $this->assertResponseOk();
    $this->assertResponseContains('<ul id="contact-list">');
    $this->assertResponseContains('Ada Lovelace');
    $this->assertResponseNotContains('Alan Turing');
}

We post the signals as an array instead of a JSON body because enableCsrfToken() injects the token into the request data, and the controller reads both through getData() anyway.

8. What about production?

A couple of things to keep in mind:

  • Buffering. If all the events arrive together at the end, something is buffering. The X-Accel-Buffering: no header takes care of nginx, stream() flushes PHP's output buffers, but zlib.output_compression or a CDN in front can still get in the middle.
  • Workers. An open stream keeps a PHP-FPM worker busy. For short jobs and progress bars this is fine. If you're planning hundreds of long lived connections (dashboards, notifications), size pm.max_children accordingly, or move those endpoints to FrankenPHP, RoadRunner or Swoole.
  • Session lock. That's why stream() closes the session first. Without it, other tabs from the same user would hang until the stream ends.
  • DebugKit only injects the toolbar into full HTML pages, so the fragments and SSE responses are not affected, and you can still inspect every request from the history panel.
  • Postgres. Unrelated to Datastar, but if you're using DDEV with Postgres, set 'encoding' => 'utf8' in your app_local.php connections. The skeleton app.php defaults to utf8mb4, which is MySQL only, and Postgres will refuse it.

Next steps

Here are a couple of ideas to keep going from here:

  • Infinite scroll, using data-on-intersect on the last row to @get() the next page and append it.
  • Inline editing, swapping a row with a small form element and back.
  • Live updates for other users, keeping a stream open and pushing changes from a queue job, with the worker caveat above.
  • Moving the component to a plugin, so you can reuse it across projects.

Datastar works well with CakePHP because it doesn't ask you to give up anything: templates and elements keep rendering the HTML, Tables and validators keep the business rules, routing, CSRF and middleware work as usual. The integration is ~150 lines of code you own, with no build step. Not bad for a few data-* attributes.

Github example repo: https://github.com/CakeDC/cakephp-datastar-example

Need help with this in your own CakePHP app?

Talk to a CakePHP expert

Get the CakeDC newsletter

One email a month: releases, security advisories and one article worth reading.

Back to all articles
We Bake with CakePHP