Upload a video to Bunny Stream and a lot happens while you grab a coffee. It gets encoded, captioned, chaptered, and Bunny Stream even picks out the best moments. Each of those steps can ping your app as it happens.
The fun part is what answers the ping. Edge Scripting lets you run small TypeScript functions, with no server to set up and nothing to keep running. Point your video library's webhook at one and every status change becomes a trigger for your own code.
Here are 20 ideas to steal, remix, or argue with. They aren't finished products… just starter scripts to get you building.
1. Sort videos into collections
With Content Tagging switched on for the library, Stream labels each video with an auto-detected category. This script finds a collection with that name, creates one if it's missing, and moves the video into it. No database needed. Without Content Tagging, every video stays untagged and is skipped.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const library = `https://video.bunnycdn.com/library/${event.VideoLibraryId}`;
const headers = {
AccessKey: process.env.STREAM_API_KEY!,
"Content-Type": "application/json",
};
const video = await fetch(`${library}/videos/${event.VideoGuid}`, { headers })
.then((res) => res.json());
const category = video.category;
if (!category || category === "untagged") return new Response("No category yet");
const found = await fetch(
`${library}/collections?search=${encodeURIComponent(category)}`,
{ headers },
).then((res) => res.json());
const collection =
found.items?.find((c: any) => c.name === category) ??
(await fetch(`${library}/collections`, {
method: "POST",
headers,
body: JSON.stringify({ name: category }),
}).then((res) => res.json()));
await fetch(`${library}/videos/${event.VideoGuid}`, {
method: "POST",
headers,
body: JSON.stringify({ collectionId: collection.guid }),
});
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
Collection names aren't unique, so two videos that finish together with a new category can each create the collection. If that matters, create your collections up front.
2. Searchable transcripts
When status 9 arrives, each caption track is a WebVTT file on the library's CDN hostname at /{video_id}/captions/{language}.vtt. Strip the timestamps and you have a transcript you can search.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 9) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
for (const caption of video.captions ?? []) {
const vtt = await fetch(
`https://${process.env.STREAM_CDN_HOSTNAME}/${video.guid}/captions/${caption.srclang}.vtt?v=${caption.version}`,
).then((res) => res.text());
const transcript = vtt
.split("\n")
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("WEBVTT") && !line.includes("-->") && !/^\d+$/.test(line))
.join(" ");
// TODO: save { videoId: video.guid, language: caption.srclang, transcript }
// to your database or search index (Bunny Database, Typesense, Meilisearch).
console.log(`${caption.srclang}: ${transcript.length} characters`);
}
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
The ?v= uses the caption's version, which goes up each time a track is replaced, so you never read a stale copy from cache. If the library uses token authentication, sign the caption URL before fetching it. Set STREAM_CDN_HOSTNAME to the library's b-cdn.net hostname. Status 9 fires once per language, so the script re-reads every track each time. Save by video and language and the repeats are harmless.
3. Review AI titles before they go live
Status 10 means Bunny Stream has written a title or description. With this you could send the new copy to copywriters in Slack so a person reads it before your site shows it:
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 10) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
await fetch(process.env.SLACK_WEBHOOK_URL!, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: `Review needed for ${video.guid}\nTitle: ${video.title}\nDescription: ${video.description ?? "(none)"}`,
}),
});
// TODO: save the title and description as a draft in your CMS or database.
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
With both title and description switched on, status 10 arrives twice, once for each, so reviewers get two messages. The first one still shows the old description.
4. Chapter navigation and shareable moments
Chapters come with title, start, and end in seconds, as well as moments with a label and timestamp. Your watch page can then obtain a chapter list and a set of links that jump to the good parts.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 12 && event.Status !== 13) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
const chapters = (video.chapters ?? []).map((c: any) => ({
title: c.title,
start: c.start,
}));
const moments = (video.moments ?? []).map((m: any) => ({
label: m.label,
url: `https://example.com/watch/${video.guid}?t=${m.timestamp}`,
}));
// TODO: save `chapters` and `moments` against the video in your database.
console.log({ chapters, moments });
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
5. Tell the uploader the moment it’s playable
Status 4 fires once per finished resolution, and the first one makes the video playable. Retries and resolutions that finish close together can all look like the first, so keep a flag per video in your database and the uploader hears about it once.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 4) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
// The webhook can arrive just before the resolution is saved.
// A 503 makes Stream retry 30 seconds later.
const resolutions = (video.availableResolutions ?? "").split(",").filter(Boolean);
if (!resolutions.length) return new Response("Not saved yet", { status: 503 });
// TODO: check an "announced" flag for event.VideoGuid in your database
// and set it now. Retries and later resolutions then stop here.
const announced = false;
if (announced) return new Response("Already announced");
// TODO: look up the uploader in your database and email them
// (Resend, Postmark, or your own provider).
console.log(`"${video.title}" is playable at ${resolutions[0]}`);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
6. Enforce upload rules
Do you have a 3-hour 240p screen recording someone uploaded by mistake? Bin it before it takes up storage. This one rejects anything over 20 minutes or under 480p.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
const MAX_SECONDS = 20 * 60;
const MIN_HEIGHT = 480;
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 2) return new Response("Ignored");
const url = `https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`;
const headers = { AccessKey: process.env.STREAM_API_KEY! };
const video = await fetch(url, { headers }).then((res) => res.json());
if (!video.length) return new Response("No duration yet");
if (video.length > MAX_SECONDS || video.height < MIN_HEIGHT) {
await fetch(url, { method: "DELETE", headers });
// TODO: tell the uploader why (email, in-app notification).
return new Response("Rejected");
}
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
7. Route vertical clips to a shorts feed
Vertical videos under a minute, such as shorts, reels, or UGC, usually live in a different feed from a 40-minute talk. The dimensions and duration are usually enough to decide what to do:
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
// Width and height are stored before rotation, and phones often report -90.
const rotated = Math.abs(video.rotation ?? 0) % 180 === 90;
const [width, height] = rotated ? [video.height, video.width] : [video.width, video.height];
const feed = height > width && video.length <= 60 ? "shorts" : "main";
// TODO: save the feed against the video in your database.
console.log(`${event.VideoGuid} goes in the ${feed} feed`);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
Get Video returns width and height as stored, before any rotation, plus a rotation value from the file's metadata. It can be 90, -90, 270, or -270, and phone videos commonly report -90, so the script swaps width and height whenever the rotation is a quarter turn.
8. Gate publishing
Stop videos going live until they play at every resolution. Status 3 is your green light!
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
const published = {
id: video.guid,
title: video.title,
duration: video.length,
publishedAt: event.Timestamp,
};
// TODO: upsert `published` into your database and mark the video as live,
// e.g. with @libsql/client/web for Bunny Database.
console.log("Published", published);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
Status 3 fires again after a re-encode or repackage, so upsert by VideoGuid and keep the original publishedAt when the row already exists.
9. Announce new videos to your fans
The same status 3 can tell people a video is out. This script posts to a Slack incoming webhook. For Discord, send content where Slack expects text:
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
await fetch(process.env.SLACK_WEBHOOK_URL!, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: `New video: ${video.title} https://example.com/watch/${video.guid}`,
}),
});
// TODO: email your subscribers too (Resend, Postmark, your newsletter tool).
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
Status 3 also fires again after a re-encode, so record each VideoGuid you've announced and skip repeats. Live stream recordings send status 3 to the same URL too.
10. Blurhash placeholders for thumbnails
Get Video returns a thumbnailUrl and a thumbnailBlurhash, a short string that decodes into a blurred preview of the thumbnail. Store both and your video grid can paint a placeholder before any image has loaded.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
const thumbnail = { url: video.thumbnailUrl, blurhash: video.thumbnailBlurhash };
// TODO: save `thumbnail` against the video in your database.
// Decode it in the browser with the `blurhash` npm package.
console.log(thumbnail);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
11. Structured data for search engines
Search engines read VideoObject JSON-LD to show video results with a thumbnail and duration, and everything they need is in the video model.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
const jsonLd = {
"@context": "https://schema.org",
"@type": "VideoObject",
name: video.title,
description: video.description ?? video.title,
thumbnailUrl: video.thumbnailUrl,
uploadDate: video.dateUploaded,
duration: `PT${video.length}S`,
embedUrl: `https://player.mediadelivery.net/embed/${event.VideoLibraryId}/${video.guid}`,
};
// TODO: store `jsonLd` with the video, then print it on your watch page
// inside <script type="application/ld+json">.
console.log(JSON.stringify(jsonLd));
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
12. Keep a video sitemap up to date
JSON-LD describes a video on its own page. A video sitemap tells search engines which pages have videos in the first place. Whenever a video finishes or is deleted, this script lists the library's playable videos and writes sitemap-videos.xml to Bunny Storage, ready to serve through a pull zone. No database needed.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
const escapeXml = (text: string) =>
text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3 && event.Status !== 32) return new Response("Ignored");
const library = `https://video.bunnycdn.com/library/${event.VideoLibraryId}`;
const headers = { AccessKey: process.env.STREAM_API_KEY! };
// A deleted video is already gone from the list, so rebuilding drops it.
const videos: any[] = [];
for (let page = 1; ; page++) {
const { items, totalItems } = await fetch(
`${library}/videos?page=${page}&itemsPerPage=1000`,
{ headers },
).then((res) => res.json());
videos.push(...items);
if (!items.length || videos.length >= totalItems) break;
}
const urls = videos
.filter((v) => v.availableResolutions && v.thumbnailUrl)
.map((v) => `<url>
<loc>https://example.com/watch/${v.guid}</loc>
<video:video>
<video:thumbnail_loc>${escapeXml(v.thumbnailUrl)}</video:thumbnail_loc>
<video:title>${escapeXml(v.title)}</video:title>
<video:description>${escapeXml(v.description || v.title)}</video:description>
<video:player_loc>https://player.mediadelivery.net/embed/${event.VideoLibraryId}/${v.guid}</video:player_loc>
<video:duration>${Math.round(v.length)}</video:duration>
</video:video>
</url>`);
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
${urls.join("\n")}
</urlset>`;
await fetch(
`https://${process.env.STORAGE_HOSTNAME}/${process.env.STORAGE_ZONE_NAME}/sitemap-videos.xml`,
{
method: "PUT",
headers: {
AccessKey: process.env.STORAGE_ZONE_PASSWORD!,
"Content-Type": "application/xml",
},
body: sitemap,
},
);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
Set STORAGE_HOSTNAME to your storage zone's region endpoint, such as storage.bunnycdn.com. Point to the sitemap from your robots.txt, and purge its URL after each write if your pull zone caches it. With token authentication switched on, crawlers can't fetch the thumbnails.
13. Retry a failed encode once, then alert
Some failures are transient, so the first status 5 for a video triggers a re-encode and the second goes to the team. Re-encoding reads the original upload, so Keep Original Files needs to be on in the library's encoding settings. It also re-queues transcription when that's switched on, which is billed again. Status 5 also covers a failed URL fetch and a rejected non-video file. Neither has an original to re-encode, so the API refuses and the script alerts the team straight away.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 5) return new Response("Ignored");
// TODO: check your database for an earlier failure of event.VideoGuid,
// and record this one.
const failedBefore = false;
if (!failedBefore) {
const res = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}/reencode`,
{ method: "POST", headers: { AccessKey: process.env.STREAM_API_KEY! } },
);
if (res.ok) return new Response("Retrying");
}
// Falls through to the alert when the re-encode is refused.
await fetch(process.env.SLACK_WEBHOOK_URL!, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: `Encoding failed for ${event.VideoGuid}` }),
});
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
14. Explain the failure to the uploader
“Encoding failed” is the “something went wrong” of video. Get Video’s transcodingMessages tell you what actually broke, so pass it on!
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 5) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
const errors = (video.transcodingMessages ?? [])
.filter((m: any) => m.level === 3) // 3 is Error
.map((m: any) => `- ${m.message}`)
.join("\n");
// Fetch failures and some upload failures have no error entry.
const problems = errors || "- No details were recorded. Try uploading the file again.";
// TODO: email the uploader with `problems` (Resend, Postmark).
console.log(`"${video.title}" failed:\n${problems}`);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
15. Catch duplicate uploads
Someone uploaded the same file twice and you’re paying to store both. originalHash catches it.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
if (!video.originalHash) return new Response("No hash");
// TODO: look up video.originalHash in your database.
// Found on another video: flag or delete this one.
// Not found: save the hash against video.guid.
console.log(`${video.guid} has hash ${video.originalHash}`);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
Status 3 fires again after a re-encode, so save the hash with an upsert keyed on VideoGuid, or the video will match itself.
16. Per-user storage quotas
storageSize is the video's total footprint in bytes, across every resolution and thumbnail, plus the original when Keep Original Files is on. Captions generated after status 3 aren't in the number yet. Store it per video and total it per user to track storage usage against their plan limit.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 3) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
const megabytes = Math.round(video.storageSize / 1_000_000);
// TODO: set video.storageSize for video.guid in your database (status 3 repeats
// on re-encode, so set rather than add), then total it per uploader
// and warn or block them when they pass their plan's limit.
console.log(`${video.guid} uses ${megabytes} MB`);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
17. Track direct uploads
With pre-signed (TUS) uploads the file goes from the browser to Bunny Stream and your backend never sees it. Statuses 6, 7, and 8 tell you what happened once it arrived: 6 means the whole file was received, 7 means it's in storage, and 8 means the copy to storage failed on Bunny Stream's side.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
const uploads = {
6: "received",
7: "stored",
8: "processing_failed",
};
async function handler(req: Request): Promise<Response> {
const event = await req.json();
const state = uploads[event.Status];
if (!state) return new Response("Ignored");
// TODO: update the upload's state in your database, keyed by event.VideoGuid.
// Detect browser-side failures in your TUS client. Status 8 means our side
// failed and the file needs to be sent again.
console.log(`${event.VideoGuid}: ${state}`);
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
18. Clean up when a video is deleted
Status 32 fires once for every deleted video, including each video inside a deleted collection. The video no longer exists by the time the event arrives, so the script works from the GUID alone.
It also purges the cached watch page from the CDN, which needs your account API key.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 32) return new Response("Ignored");
// TODO: delete the video's rows from your database and search index.
const page = `https://example.com/watch/${event.VideoGuid}`;
await fetch(`https://api.bunny.net/purge?url=${encodeURIComponent(page)}`, {
method: "POST",
headers: { AccessKey: process.env.BUNNY_API_KEY! },
});
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
19. Pull quotes for social posts
Stream's moments are picked by Stream. With the transcript and your own model, you choose what counts as a highlight. This script keeps each caption line's start time, asks your model for the most quotable lines, and turns each one into a post that links to that point in the video. It picks the track from video.captions, because auto-generated captions are stored as {lang}-auto.vtt. Add a per-video flag in your database too, because status 9 fires once per language.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
function toSeconds(time: string) {
const [h, m, s] = time.split(":");
return Number(h) * 3600 + Number(m) * 60 + Math.floor(Number(s));
}
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 9) return new Response("Ignored");
const video = await fetch(
`https://video.bunnycdn.com/library/${event.VideoLibraryId}/videos/${event.VideoGuid}`,
{ headers: { AccessKey: process.env.STREAM_API_KEY! } },
).then((res) => res.json());
// Auto-generated tracks are listed as "en-auto", uploaded ones as "en".
const caption = (video.captions ?? []).find((c: any) => c.srclang.startsWith("en"));
if (!caption) return new Response("No English captions yet");
// TODO: check a "quotes done" flag for event.VideoGuid in your database
// and set it now. Status 9 fires once per language.
const done = false;
if (done) return new Response("Already done");
const vtt = await fetch(
`https://${process.env.STREAM_CDN_HOSTNAME}/${video.guid}/captions/${caption.srclang}.vtt?v=${caption.version}`,
).then((res) => res.text());
// Cues can be separated by more than one blank line.
// Keep each cue's start time so the model can point back into the video.
const lines = vtt.split(/\n{2,}/).flatMap((cue) => {
const [timing, ...text] = cue.split("\n").filter((l) => l.trim() && !/^\d+$/.test(l));
if (!timing?.includes("-->")) return [];
return [`[${toSeconds(timing.split(" --> ")[0])}] ${text.join(" ")}`];
});
// TODO: send `lines.join("\n")` to your model (OpenAI, Anthropic, a self-hosted one)
// and ask for the three most quotable lines as JSON: [{ "quote": "...", "start": 83 }].
const quotes = [{ quote: "Example quote", start: 83 }];
for (const { quote, start } of quotes) {
const link = `https://example.com/watch/${event.VideoGuid}?t=${start}`;
// TODO: save as a draft post in your scheduler, or render a share card.
console.log(`"${quote}" ${link}`);
}
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
The same timestamped transcript works for any prompt you like, such as a summary for the watch page, key takeaways for a newsletter, or answers to the questions viewers ask most.
20. Recover from failed captions and AI features
Status 11 means automatic captions failed. Status 33 means a smart feature failed, and its Reason names which one: Title, Description, Chapters, or Moments. This script tells the team what's missing so the watch page doesn't quietly ship without it.
import * as BunnySDK from "@bunny.net/edgescript-sdk";
import process from "node:process";
async function handler(req: Request): Promise<Response> {
const event = await req.json();
if (event.Status !== 11 && event.Status !== 33) return new Response("Ignored");
const feature = event.Status === 11 ? "Captions" : event.Reason;
// TODO: mark the feature as missing on the video in your database,
// so your watch page can hide the captions or chapters UI.
await fetch(process.env.SLACK_WEBHOOK_URL!, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: `${feature} generation failed for ${event.VideoGuid}` }),
});
return new Response("OK");
}
BunnySDK.net.http.serve(handler);
After a status 11, call Transcribe again. It needs Keep Original Files switched on, and force=true only when an auto caption track already exists. After a status 33, call Trigger Smart Actions with the feature that failed, which reuses the captions you already have.
Verify the signature before you ship
The code examples above trust whatever arrives, so you’ll want to make sure to verify it was Bunny Stream that sent you the events by verifying its signature.
Stream signs the raw body with HMAC-SHA256, uses the video library’s Read-Only API key as the secret, and sends v1 in X-BunnyStream-Signature-Version. Add the key as STREAM_READ_ONLY_KEY and paste this function into any script, above the final serve line:
import process from "node:process";
async function isFromStream(req: Request, body: string) {
const signature = req.headers.get("X-BunnyStream-Signature") ?? "";
if (req.headers.get("X-BunnyStream-Signature-Version") !== "v1") return false;
if (!/^[0-9a-f]{64}$/.test(signature)) return false;
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(process.env.STREAM_READ_ONLY_KEY!),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"],
);
const bytes = Uint8Array.from(signature.match(/../g)!, (h) => parseInt(h, 16));
return crypto.subtle.verify("HMAC", key, bytes, encoder.encode(body));
}
You will want to swap the const event = await req.json(); line for these three:
const body = await req.text();
if (!(await isFromStream(req, body))) {
return new Response("Invalid signature", { status: 401 });
}
const event = JSON.parse(body);
The check runs on the raw text before JSON.parse, because parsing and re-serializing can change the bytes and break the signature.
Bunny Stream retries a delivery that fails or times out up to six times over roughly four hours. It retries on network errors, timeouts, 408, 429, and 5xx responses. Any other 4xx counts as final, so return a 5xx when something on your side fails temporarily. Every retry carries the same EventId, so store the IDs you've handled if running a script twice would cause harm, such as sending the same email again.
Every video status
Each Bunny Stream webhook carries a numeric Status which you can build on:
| Status | Name | When it fires |
|---|---|---|
| 0 | Queued | The video is queued for encoding |
| 1 | Processing | Stream is reading the file's format and building previews |
| 2 | Encoding | Encoding has started |
| 3 | Finished | Every resolution is encoded. Fires again after a re-encode |
| 4 | Resolution finished | One resolution is done, and the first one makes the video playable |
| 5 | Failed | Encoding, a URL fetch, or file validation failed |
| 6, 7, 8 | Upload received, stored, storage failed | A direct (TUS) upload reached Bunny Stream, was saved to storage, or failed to save |
| 9 | Captions generated | Captions for one language are ready. Sent once per language |
| 10 | Title or description generated | AI metadata is ready. Sent separately for the title and the description |
| 11 | Caption generation failed | Automatic captions failed |
| 12 | Chapters generated | AI chapters are ready |
| 13 | Moments generated | AI moments are ready |
| 32 | Video deleted | Sent once per video, including videos removed with their collection |
| 33 | Smart generation failed | Reason names the feature: Title, Description, Chapters, or Moments |
The body is small and tells you which video changes and how:
{
"VideoLibraryId": 123456,
"VideoGuid": "657bb740-a71b-4529-a012-528021c31a92",
"Status": 3,
"EventId": "<unique per event, stable across retries>",
"Timestamp": "<UTC time the event happened>",
"IsLiveStreamWebhook": false
}
For the title, duration, dimensions, captions, chapters, thumbnail, storage zone, and anything else, you can call Get Video with the VideoGuid.
Things to know
The status field that Get Video returns isn't the same as the webhook's Status, so don't mix the two up. Status 3 can repeat, so key on VideoGuid and upsert.
Webhooks fire for uploads, processing, AI features, and deletion. Views, watch time, and heatmaps don't send anything, so if your app needs those numbers, pull them from the statistics endpoints.
Bunny Live Streams send statuses 14 to 31 to the same URL, with IsLiveStreamWebhook: true. I’ll write about some ideas using Edge Scripting for those in another post.
One URL, lots of ideas
A video library sends all its webhooks to a single URL. That means if you want more than one of these ideas running at once, you need one script that receives every event and passes it to each idea. Several ideas listen for the same status, and each one already ignores the statuses it doesn't need, so in pseudocode it looks like this:
const ideas = [catchDuplicates, sortIntoCollection, announceVideo, indexTranscript];
for (const idea of ideas) {
await idea(event); // each idea checks event.Status itself
}
return new Response("OK");
This is the simplest version. If one idea fails and you return a 5xx, Stream retries the event and every idea runs again, including the ones that already worked. Once you have more than a couple of ideas, or one of them does heavy lifting like a long LLM call, reply to the webhook straight away and put one job per idea on a queue. Each job can then retry on its own without repeating the others. Magic Containers is a great fit for running that worker!
Start with one
Every idea in this post lives in the bunny.net examples repo as its own Edge Script. Pick the one closest to what you need, tweak it, build on it and deploy it:
cd stream/webhook-auto-collections
npm install
bunny scripts create my-stream-webhook --type standalone
npm run deploy
Upload a test video, grab that coffee, and watch your script do its thing. If you’re using Bunny Stream webhooks in a different way, open a PR in the examples repo and share what you’ve built in Discord.
Comments require cookies. to view and post.

