Skip to main content

Installation

npm install --save @streamstraight/client

Usage

Ensure your frontend can fetch the streamId you used on the server and expose an endpoint that returns a client JWT. Provide that fetcher to the SDK so it can refresh tokens whenever it reconnects.
import { connectStreamstraightClient } from "@streamstraight/client";

// Type each chunk however you want; you're not tied
// to the OpenAI example here. Just make sure the type
// matches what you pass to Streamstraight on your server.
type ChunkType = OpenAI.Responses.ResponseStreamEvent;

async function fetchStreamstraightToken(): Promise<string> {
  const response = await fetch("/api/streamstraight-token", { method: "POST" });
  if (!response.ok) {
    throw new Error("Failed to fetch Streamstraight token");
  }
  const { token } = (await response.json()) as { token: string };
  return token;
}

async function stream(streamId: string) {
  const ssClient = await connectStreamstraightClient<ChunkType>(
    { fetchToken: fetchStreamstraightToken },
    { streamId },
  );

  for await (const chunk of ssClient.toAsyncIterable()) {
    // Handle each chunk as it's streamed
  }
}