Crux
API Reference

@use-crux/react/server

Server-side SSE handler for streaming RecordStore changes to the browser.

import { cruxSSEHandler } from "@use-crux/react/server";
import type { CruxSSEHandlerOptions } from "@use-crux/react/server";

Overview

The server subpath provides cruxSSEHandler() -- a Server-Sent Events endpoint that subscribes to RecordStore.subscribe() and streams data-crux events to connected clients. Pair it with createSSETransport() on the client side for real-time reactive updates.

cruxSSEHandler(options)

Create an SSE endpoint handler for streaming RecordStore changes. Returns a function compatible with Next.js App Router GET handlers, or any framework that expects (request: Request) => Response.

ParameterTypeDescription
options.storeRecordStoreThe RecordStore to subscribe to. Must implement subscribe().
options.prefixstring?Key prefix filter. Only events for matching keys are sent. Default: '' (all events).

Returns: (request: Request) => Response

The handler returns HTTP 501 if the store does not implement subscribe().

Event Format

Events are sent as data-crux named events with JSON payloads:

event: data-crux
data: {"entity":"plan","key":"plan:abc","value":{...},"event":"set"}
FieldTypeDescription
entity'plan' | 'taskLedger' | 'task'Entity type classified from the key
keystringThe full store key
valueJsonObject | nullThe value (null for deletes)
event'set' | 'delete'The event type

Key Classification

The handler classifies store keys into entity types:

Key PrefixEntity
plan:plan
task ledger keystaskLedger
task:task

Keys that don't match any known prefix are silently skipped.

Usage with Next.js App Router

app/api/crux/events/route.ts
import { cruxSSEHandler } from "@use-crux/react/server";
import { store } from "@/lib/store";

// Stream all store changes
export const GET = cruxSSEHandler({ store });
app/api/crux/plans/route.ts
import { cruxSSEHandler } from "@use-crux/react/server";
import { store } from "@/lib/store";

// Stream only plan events
export const GET = cruxSSEHandler({ store, prefix: "plan:" });

Client Integration

Pair with createSSETransport() from @use-crux/react:

import { createSSETransport, CruxProvider } from "@use-crux/react";

const transport = createSSETransport("/api/crux/events");

function App() {
  return (
    <CruxProvider transport={transport}>
      <PlanView planId="abc" />
    </CruxProvider>
  );
}

Types

import type { CruxSSEHandlerOptions } from "@use-crux/react/server";

CruxSSEHandlerOptions

FieldTypeDescription
storeRecordStoreThe RecordStore to subscribe to. Must implement subscribe().
prefixstring?Key prefix filter. Default: ''.

On this page