Implementing Datastar: set headers in route

I am currently playing around with the Hypermedia framework Datastar. D* works with Server Sent Events (SSE) and has a dedicated PHP SDK. It needs needs to set a couple of headers and I can’t quite figure out how to integrate this with Kirby’s router.

This is a route I have set up. Creating a new ServerSentEventGenerator will run the headers logic, which conflicts with Kirby’s built-in Response class and throws this error: Cannot set response code - headers already sent

[
            'pattern' => '/datastar/(:any)',
            'action' => function ($slug) {
                $sse = new ServerSentEventGenerator();
                $sse->sendHeaders();
                $sse->mergeFragments('<div>Foo</div>');
            }
        ]

Does anyone have an idea how to handle this or point me in a direction where I can learn more about Kirby’s response process?

Seems to have been my mistake all along. I was looking at the wrong end and didn’t realize that the route I was calling still had a template/view attached, which means Kirby created a second route that was called right after mine, which is where the response came from. This works perfectly fine in a standalone route:

[
            'pattern' => '/test',
            'action' => function () {
                $sse = new ServerSentEventGenerator();
                $sse->mergeFragments('<div>Foo</div>');
            }
]
2 Likes