Skip to Content
Backend

Stream data to your backend (AI, files)

Read AI/LLM output, file chunks, and other streaming data from your Trigger.dev tasks in backend code.

Read streaming data from your tasks in backend code. Consume AI completions as they generate, process file chunks, or handle any continuous data your tasks produce.

To emit streams from your tasks, see Streaming data from tasks. For React components, see Streaming in React.

Run-scoped streams are the right primitive for ephemeral I/O that lives inside a single run's lifetime. For durable, long-lived channels that outlive a run, see chat.agent: it's built on a Session row that owns the chat's runs and exposes bidirectional .in / .out channels addressed by a durable id.

Reading streams

The recommended approach is to use defined streams for full type safety:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function consumeStream(runId: string) {
  // Read from the defined stream
  const stream = await .read(runId);

  let fullText = "";

  for await (const chunk of stream) {
    .("Received chunk:", chunk); // chunk is typed!
    fullText += chunk;
  }

  .("Final text:", fullText);
}

Direct stream reading

If you prefer not to use defined streams, you can read directly by specifying the stream key:

import {  } from "@trigger.dev/sdk";

async function consumeStream(runId: string) {
  // Read from a stream by key
  const stream = await .read<string>(runId, "ai-output");

  for await (const chunk of stream) {
    .("Received chunk:", chunk);
  }
}

Reading from the default stream

Every run has a default stream, so you can omit the stream key:

import {  } from "@trigger.dev/sdk";

async function consumeDefaultStream(runId: string) {
  // Read from the default stream
  const stream = await .read<string>(runId);

  for await (const chunk of stream) {
    .("Received chunk:", chunk);
  }
}

Stream options

The read() method accepts several options for controlling stream behavior:

Timeout

Set a timeout to stop reading if no data is received within a specified time:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function consumeWithTimeout(runId: string) {
  const stream = await .read(runId, {
    timeoutInSeconds: 120, // Wait up to 2 minutes for data
  });

  for await (const chunk of stream) {
    .("Received chunk:", chunk);
  }

  // The loop ends normally if no data arrives within the timeout
}

If no data arrives within timeoutInSeconds, the stream closes and the for await loop ends without throwing an error. To detect a timeout, track whether you received the chunk you expected to be last.

Start index

Resume reading from a specific chunk index (useful for reconnection scenarios):

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function resumeStream(runId: string, lastChunkIndex: number) {
  // Start reading from the chunk after the last one we received
  const stream = await .read(runId, {
    startIndex: lastChunkIndex + 1,
  });

  for await (const chunk of stream) {
    .("Received chunk:", chunk);
  }
}

Start from latest

Pass from: "latest" to start reading at the end of the stream instead of replaying its history. You may still receive the most recent existing chunk before new chunks arrive. The default is "beginning", which replays the full history first. from is ignored when startIndex is set:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function watchLive(runId: string) {
  const stream = await .read(runId, {
    from: "latest", // Start at the end of the stream instead of replaying history
  });

  for await (const chunk of stream) {
    .("Received chunk:", chunk);
  }
}

Abort signal

Use an AbortSignal to cancel stream reading:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function consumeWithCancellation(runId: string) {
  const controller = new ();

  // Cancel after 30 seconds
  (() => controller.(), 30000);

  const stream = await .read(runId, {
    signal: controller.,
  });

  try {
    for await (const chunk of stream) {
      .("Received chunk:", chunk);

      // Optionally abort based on content
      if (chunk.includes("STOP")) {
        controller.();
      }
    }
  } catch (error) {
    if (error.name === "AbortError") {
      .("Stream was cancelled");
    }
  }
}

Combining options

You can combine multiple options:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function advancedStreamConsumption(runId: string) {
  const controller = new ();

  const stream = await .read(runId, {
    timeoutInSeconds: 300, // 5 minute timeout
    startIndex: 0, // Start from the beginning
    signal: controller., // Allow cancellation
  });

  try {
    for await (const chunk of stream) {
      .("Received chunk:", chunk);
    }
  } catch (error) {
    if (error.name === "AbortError") {
      .("Stream was cancelled");
    } else {
      .("Stream error:", error);
    }
  }
}

Practical examples

Reading AI streaming responses

Here's a complete example of consuming an AI stream from your backend:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function consumeAIStream(runId: string) {
  const stream = await .read(runId, {
    timeoutInSeconds: 300, // AI responses can take time
  });

  let fullResponse = "";
  const chunks: string[] = [];

  for await (const chunk of stream) {
    chunks.(chunk);
    fullResponse += chunk;

    // Process each chunk as it arrives
    .("Chunk received:", chunk);

    // Could send to websocket, SSE, etc.
    // await sendToClient(chunk);
  }

  .("Stream complete!");
  .("Total chunks:", chunks.);
  .("Full response:", fullResponse);

  return { fullResponse, chunks };
}

Reading multiple streams

If a task emits multiple streams, you can read them concurrently or sequentially:

import {  } from "@trigger.dev/sdk";
import { ,  } from "./trigger/streams";

async function consumeMultipleStreams(runId: string) {
  // Read streams concurrently
  const [aiData, progressData] = await .([
    consumeStream(, runId),
    consumeStream(, runId),
  ]);

  return { aiData, progressData };
}

async function consumeStream<T>(
  streamDef: { read: (runId: string) => Promise<AsyncIterableStream<T>> },
  runId: string
): Promise<T[]> {
  const stream = await streamDef.read(runId);
  const chunks: T[] = [];

  for await (const chunk of stream) {
    chunks.(chunk);
  }

  return chunks;
}

Piping streams to HTTP responses

You can pipe streams directly to HTTP responses for server-sent events (SSE):

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";
import type {  } from "next/server";

export async function GET(request: ) {
  const runId = request.nextUrl.searchParams.("runId");

  if (!runId) {
    return new ("Missing runId", { status: 400 });
  }

  const stream = await .read(runId, {
    timeoutInSeconds: 300,
  });

  // Create a readable stream for SSE
  const encoder = new ();
  const readableStream = new ({
    async start(controller) {
      try {
        for await (const chunk of stream) {
          // Format as SSE
          const data = `data: ${.({ chunk })}\n\n`;
          controller.(encoder.(data));
        }
        controller.();
      } catch (error) {
        controller.(error);
      }
    },
  });

  return new (readableStream, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      "Connection": "keep-alive",
    },
  });
}

Implementing retry logic

Handle transient errors with retry logic:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function consumeStreamWithRetry(
  runId: string,
  maxRetries = 3
): Promise<string[]> {
  let lastChunkIndex = 0;
  const allChunks: string[] = [];
  let attempt = 0;

  while (attempt < maxRetries) {
    try {
      const stream = await .read(runId, {
        startIndex: lastChunkIndex,
        timeoutInSeconds: 120,
      });

      for await (const chunk of stream) {
        allChunks.(chunk);
        lastChunkIndex++;
      }

      // Success! Break out of retry loop
      break;
    } catch (error) {
      attempt++;

      if (attempt >= maxRetries) {
        throw new Error(`Failed after ${maxRetries} attempts: ${error.message}`);
      }

      .(`Retry attempt ${attempt} after error:`, error.message);

      // Wait before retrying (exponential backoff)
      await new ((resolve) => (resolve, 1000 * .(2, attempt)));
    }
  }

  return allChunks;
}

Processing streams in chunks

Process streams in batches for efficiency:

import {  } from "@trigger.dev/sdk";
import {  } from "./trigger/streams";

async function processStreamInBatches(runId: string, batchSize = 10) {
  const stream = await .read(runId);

  let batch: string[] = [];

  for await (const chunk of stream) {
    batch.(chunk);

    if (batch. >= batchSize) {
      // Process the batch
      await processBatch(batch);
      batch = [];
    }
  }

  // Process remaining chunks
  if (batch. > 0) {
    await processBatch(batch);
  }
}

async function processBatch(chunks: string[]) {
  .(`Processing batch of ${chunks.} chunks`);
  // Do something with the batch
  // e.g., save to database, send to queue, etc.
}

Using with runs.subscribeToRun()

For more advanced use cases where you need both the run status and streams, you can use the runs.subscribeToRun() method with .withStreams():

import {  } from "@trigger.dev/sdk";
import type {  } from "./trigger/myTask";

async function subscribeToRunAndStreams(runId: string) {
  for await (const update of .subscribeToRun<typeof >(runId).withStreams()) {
    switch (update.type) {
      case "run":
        .("Run update:", update.run.status);
        break;
      case "default":
        .("Stream chunk:", update.chunk);
        break;
    }
  }
}

For most use cases, we recommend using streams.read() with defined streams for better type safety and clearer code. Use runs.subscribeToRun().withStreams() only when you need to track both run status and stream data simultaneously.

Was this page helpful?

Last updated

Edit on GitHub

On this page