Skip to main content

JavaScript and TypeScript SDK

crumbcast on npm is the API for JavaScript and TypeScript: every endpoint a project's API token reaches, typed, plus uploads in parts, webhook checks, and analytics for a player of your own. It runs on Node 20 and later, Deno, Bun and edge runtimes, and has no dependencies: it uses the platform's fetch and Web Crypto.

Installing​

npm install crumbcast

It's an ES module, with its types in the package.

Making a client​

One Crumbcast per token, made once and used for every request:

import { Crumbcast } from "crumbcast";

const crumbcast = new Crumbcast({
token: process.env.CRUMBCAST_TOKEN!, // a project's API token, cc_…
baseUrl: "https://your-crumbcast",
});
OptionWithout it
tokenA project's API token (cc_…), from its Settings → API tokensRequired
baseUrlYour Crumbcast's address, as you open it in the browser (not /api/v1/)Required
retriesHow many times a request is sent again when Crumbcast answers 429 or 5032
fetchA fetch of your own: a proxy's, or a test'sThe platform's

The token acts as its maker, in its project, at its role: read it from the environment, on your servers only. The SDK runs in a browser too, but a token on a page is a token anyone who opens it can take. Use it there only in tools for your own team.

Calling the API​

The API is grouped as the reference is, one group per section, each method named after its endpoint: Get Video is crumbcast.videos.getVideo.

const { projects } = await crumbcast.projects.listProjects();

const { videos } = await crumbcast.videos.listVideos({ project_id: projectId, search: "launch" });

const video = await crumbcast.videos.getVideo({ id: videoId });

await crumbcast.videos.updateVideo({
id: videoId,
videoUpdateRequest: { title: "Launch day", label_ids: [labelId] },
});

Lists of videos (and the trash) come a page at a time, up to limit (100 at most). Each page's next_cursor, passed as after with the same filters and order, asks for the next one; it's null on the last. previous_cursor, as before, goes back.

let after: string | undefined;
do {
const page = await crumbcast.videos.listVideos({ project_id: projectId, limit: 100, after });
for (const video of page.videos) console.log(video.id);
after = page.next_cursor ?? undefined;
} while (after);
Group
videosUploading, importing, editing and deleting videos; their formats, captions, GIFs, protection and watermarks
liveLive streams, their broadcasts, schedules and simulcast targets
playlistsPlaylists and their videos
folders, labelsWhere videos are filed
workflowsWorkflows and their runs
webhooksWebhooks, their deliveries and tests
analyticsA project's, a video's and a broadcast's numbers
playbackWhat players load: playback links, HLS playlists, viewings
projectsThe token's project: its overview, signing keys, players, ad tags and watermarks
integrationsConnected YouTube, Twitch and Zoom accounts

Each method takes one object:

  • the path's parameters and the query's, by the names the reference gives them (id, project_id, search);
  • the request's body under its type's name, starting lowercase: Update Video's body is a VideoUpdateRequest, so it's videoUpdateRequest. Your editor completes it.

A method answers with the API's JSON as it is, typed with the reference's names:

import type { VideoResponse, CreateVideoRequest } from "crumbcast";

Fields are only ever added to answers. One newer than your copy of the SDK is in the object already; its type comes with the next version.

Errors​

A request Crumbcast refuses throws a CrumbcastError: its message is the API's reason, as the dashboard would show it, with the answer's status and its whole body.

import { CrumbcastError } from "crumbcast";

try {
await crumbcast.videos.trimVideo({ id: videoId, trimRequest: { ranges: [{ start: 10, end: 90 }] } });
} catch (error) {
if (error instanceof CrumbcastError && error.status === 409) {
console.log("Not now:", error.message);
} else {
throw error;
}
}

A 422's message names each field that's wrong and why (size: …; title: …). A 429 or 503 means Crumbcast did nothing and asks to be tried a little later: the SDK waits as long as its Retry-After says, or a little longer each time, and sends it again up to retries times before throwing. When there's no answer at all (the network failed), the error is fetch's own. Errors has what each status means.

Uploading a video​

uploadVideo does the three calls an upload takes in one: it creates the video, sends its file in parts straight to storage, and starts encoding. It answers with the video, as Complete Upload does.

import { openAsBlob } from "node:fs";

const video = await crumbcast.uploadVideo(
projectId,
await openAsBlob("launch.mp4", { type: "video/mp4" }),
{ title: "Launch day", name: "launch.mp4" },
{ onProgress: ({ uploaded, total }) => console.log(`${Math.round((uploaded / total) * 100)}%`) },
);

openAsBlob reads each part from disk as it's sent, so a large file never sits in memory.

The third argument takes everything Create Video does (folder, labels, who may watch, encodings, a workflow: see What to pick), but the file's size and type, which come from the file. A name is needed unless the file is a File.

OptionWithout it
concurrencyParts sent at once4
retriesHow many times a part is sent again before the upload fails3
onProgressCalled with { uploaded, total }, in bytes, as each part is inNone
signalAn AbortSignal that stops the parts still goingNone

A part that fails is sent again on its own; its URL is signed again if it ran out. A part that fails for good stops the others and throws. The video is there, waiting for its file: upload it again with replaceVideoFile, or delete it.

Replacing a file​

await crumbcast.replaceVideoFile(videoId, await openAsBlob("launch-v2.mp4"), { name: "launch-v2.mp4" });

The video plays as it was until the new file is encoded, and keeps its ID, links and settings. It takes the same options as uploadVideo. An upload that failed half way is given up with crumbcast.videos.cancelReplacingVideoFile({ id: videoId }).

Other files​

A thumbnail, a captions file, a player's logo: any endpoint that takes a file takes a Blob (or a File) in its form.

await crumbcast.videos.uploadCaptions({
id: videoId,
uploadCaptionsForm: { language: "en", file: await openAsBlob("launch.en.vtt") },
});

Checking webhooks​

verifyWebhook checks a delivery is your webhook's and recent, then answers with its event. Hand it the body exactly as it came, before any JSON parsing: the signature is over those bytes.

// app/crumbcast/route.ts
import { verifyWebhook, WebhookVerificationError } from "crumbcast";

export async function POST(request: Request) {
let event;
try {
event = await verifyWebhook(
await request.text(),
request.headers.get("Crumbcast-Signature"),
process.env.CRUMBCAST_WEBHOOK_SECRET!,
);
} catch (error) {
if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
throw error;
}

if (event.type === "video.ready") await markPlayable(event.data.video.id);
return new Response(null, { status: 204 });
}

It throws a WebhookVerificationError when the Crumbcast-Signature header is missing, isn't the webhook's, or the delivery is more than 5 minutes old ({ tolerance }, in seconds, changes that). The event's type tells its data apart: inside if (event.type === "video.encoded"), TypeScript knows event.data.failed is there. Each type and its data are in Events.

Answer within 10 seconds and do the work afterwards; skip an event whose id you've already handled, as Answer quickly says.

Analytics for a player of your own​

crumbcast/analytics runs in the viewer's browser, with no token, and reports what a video element plays, as Crumbcast's own player does (Players of your own):

import { track } from "crumbcast/analytics";

const stop = track(document.querySelector("video")!, {
baseUrl: "https://your-crumbcast",
video: videoId,
// A signed video's playback token, as its playlist takes
token,
});

It works with whatever plays into the element: hls.js, Shaka Player, Video.js, Plyr or the browser itself. It starts a viewing at the first play, then sends a beat every 15 seconds while playing, and on a pause, a seek, the end, and the page being hidden or closed. stop() sends what's left and stops listening: call it before playing another video in the same element, then track that one. It needs no API token, so never put one in the page.

Testing your code​

Pass a fetch of your own to answer for Crumbcast, with nothing sent:

const crumbcast = new Crumbcast({
token: "cc_test",
baseUrl: "https://crumbcast.test",
fetch: async (input) => {
const request = new Request(input);
if (request.url.endsWith(`/api/v1/videos/${videoId}/`)) return Response.json({ id: videoId, title: "Launch day" });
return Response.json({ detail: "Not found" }, { status: 404 });
},
});

For webhooks, verifyWebhook takes { now } (Unix seconds), so a delivery signed in a fixture stays recent.

Versions​

The SDK is generated from the API's OpenAPI spec, and a new version follows each change to it. Its methods and types are the reference's: when they differ, the reference is the newer.