• English
  • SSE

    Planned APIs: This page documents the final SSE workflow. commflow@0.0.2 does not export an SSE runtime; do not use its imports as current production imports. See Current Release Quick Start for runnable exports.

    When To Use It

    SSE fits server-to-client event delivery:

    ScenarioFit
    Notifications, state updates, job progressYes
    Server-to-client one-way event streamsYes
    HTTP streaming works better through browsers or gatewaysYes
    Client also needs to send continuous messagesUse Socket
    One-shot request/responseUse Request

    Create An SSE Client

    import { createCommflowSseClient } from 'commflow';
    
    const sse = createCommflowSseClient({
      baseURL: 'https://events.example.com',
      reconnect: {
        attempts: 5,
        delay: 1000
      }
    });
    OptionUser meaning
    baseURLEvent service URL.
    reconnect.attemptsMaximum reconnect attempts after disconnect.
    reconnect.delayBase reconnect delay.

    Subscribe To Events

    const stream = sse.subscribe('/notifications', {
      onMessage(event) {
        console.log(event.type, event.data);
      },
      onError(error) {
        console.error('sse failed', error);
      }
    });

    The returned stream must expose a close operation so users can release the connection on unmount, service shutdown, or task completion.

    Handle Event Types

    const stream = sse.subscribe('/jobs/42/events', {
      onMessage(event) {
        if (event.type === 'job.progress') {
          updateProgress(event.data.percent);
        }
    
        if (event.type === 'job.done') {
          markDone(event.data.result);
        }
      }
    });

    Prefer structured event types instead of treating every event as an untyped string.

    Auth And Last-Event-ID

    const stream = sse.subscribe('/jobs/42/events', {
      headers: {
        authorization: `Bearer ${token}`
      },
      lastEventId: resumeFromLastSeenId(),
      onMessage(event) {
        rememberLastSeenId(event.id);
      }
    });
    FieldTarget behavior
    headersSend auth, tenant, or trace headers when connecting.
    lastEventIdResume from the last consumed event after disconnect.
    event.idStore it in business state or at least the current session.
    onMessageMessage handling failure should enter an observable error path.

    Reconnect Policy

    An SSE disconnect is not always business failure; it may be a short network interruption.

    ScenarioGuidance
    Short network breakReconnect automatically.
    Auth expirySurface to business code, refresh token, then resubscribe.
    Non-recoverable server errorStop reconnecting and notify the user.
    Page or task endedClose manually and do not reconnect.

    State model:

    StateMeaning
    connectingEstablishing the HTTP event stream.
    openConnected and receiving events.
    reconnectingWaiting for the next connection after a non-manual close.
    closedUser closed it or the task ended.
    failedReconnect exhausted or a non-recoverable error occurred.

    Close And Cleanup

    await stream.close();

    Always release the stream when:

    • a frontend component unmounts;
    • a server request lifecycle ends;
    • user switches tenant, project, or topic;
    • a task completes and progress events are no longer needed.

    Error Handling

    SSE errors should be distinguishable:

    ErrorHandling
    Network disconnectReconnect by retry policy.
    Server rejectionSurface to business code.
    Message parse failureRecord raw message and topic for diagnostics.
    Retry exhaustedEnter final failed state.

    See Errors And Retries for the broader error model.

    When Not To Use SSE

    If you need continuous client-to-server messages, rooms, binary data, or strongly interactive realtime channels, use Socket instead of emulating a duplex protocol with SSE.