Supabase
Add video uploads and playback to your Supabase app.
Supabase Storage holds files, but it does not transcode video. Chunkify adds that step: your users upload to your Supabase bucket, Chunkify creates an HLS stream with a poster and timeline previews in the same bucket, and viewers play it from Supabase's CDN.
The video files stay in your Supabase project. Chunkify reads and writes them through Supabase's S3-compatible API.
This guide uses these Supabase features:
- Storage for the original videos and the generated streams.
- Auth to decide who can upload.
- Edge Functions to create upload sessions and receive Chunkify webhooks, in one
chunkifyfunction. - Database with row-level security, so only the Edge Function can change videos.
You need a Chunkify Project and a Supabase project with the Supabase CLI linked to it.
How it works
- A signed-in user selects a video. The
chunkifyEdge Function's/uploadsroute checks the user, adds a row to yourvideostable, and creates a Chunkify Upload session. - Chunkify Uploader sends the file from the browser straight to your Supabase bucket.
- Chunkify creates a video asset from the upload and writes its HLS stream, poster, and timeline previews to Supabase Storage.
- The function's
/webhookroute receives Chunkify's events and saves the playback URLs on the video's row. - Your app reads the row and plays the stream with Chunkify Player.
Connect Supabase Storage
Create a public bucket named videos in Supabase Storage. Then, in Storage → S3, check that S3 protocol connection is on and create an access key.
In Chunkify, open Project settings → Storage, select New storage, and choose S3-compatible. Enter:
- Endpoint URL:
https://<project-ref>.storage.supabase.co/storage/v1/s3, as shown in Supabase's Storage → S3 page. - Provider region: the region shown on the same page.
- Bucket:
videos. - Access key and Secret key: the S3 access key you created.
- CDN base URL:
https://<project-ref>.supabase.co/storage/v1/object/public/videos.
Chunkify recognizes the Supabase endpoint and shows the connection as Supabase Storage. Make it the Project default. The /uploads route doesn't name a storage, so Chunkify stores the original uploads and writes the generated streams to this bucket.
Anyone with a URL can read objects in a public bucket, including the original uploads.
Create the videos table
Run this SQL in the Supabase SQL editor or in a migration. The Data API needs explicit table grants even when row-level security (RLS) is configured. The Edge Function uses the service role to read, insert and update rows. Viewers don't need to sign in: the public read policy and column grants let the player query playback information.
create table public.videos (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users on delete cascade,
title text,
status text not null default 'uploading',
upload_id text,
source_id text,
asset_id text,
playback_url text,
poster_url text,
thumbnails_url text,
created_at timestamptz not null default now()
);
alter table public.videos enable row level security;
create policy "Anyone can read videos"
on public.videos
for select
to anon, authenticated
using (true);
grant select, insert, update on table public.videos to service_role;
grant select (id, playback_url, poster_url, thumbnails_url, created_at)
on table public.videos to anon, authenticated;
status moves from uploading to processing, then playable when the stream can start and ready when the poster and timeline previews are available. It is failed if Chunkify cannot prepare the video.
Add your Chunkify secrets
In Chunkify, create a Project access token in Developers → API tokens. Then open Developers → Webhooks → Setup webhook, enter your function URL, https://<project-ref>.supabase.co/functions/v1/chunkify/webhook, and select asset.playback_ready, asset.ready, and asset.failed under Assets and upload.completed under Uploads.
Copy the webhook secret from Webhook secret on the same page.
Save the token and the webhook secret as Edge Function secrets:
supabase secrets set \
CHUNKIFY_PROJECT_TOKEN=your-project-token \
CHUNKIFY_WEBHOOK_SECRET=your-webhook-secret
Edge Functions already have SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY. Keep the Chunkify token and the service role key out of browser code.
Create upload sessions
The function lives in supabase/functions/chunkify/. index.ts sends each request to its route:
import { createChunkifyUpload } from './uploads.ts';
import { handleChunkifyWebhook } from './webhook.ts';
Deno.serve((req) => {
const { pathname } = new URL(req.url);
if (pathname.endsWith('/uploads')) {
return createChunkifyUpload(req);
}
if (pathname.endsWith('/webhook')) {
return handleChunkifyWebhook(req);
}
return new Response('Not found', { status: 404 });
});
The /uploads route receives the file's name and size from the browser. It uses the Supabase access token sent by supabase-js to identify the user, creates the video row, and asks Chunkify for an Upload session. The row's ID goes in the Upload metadata, so the webhook can find the row again.
Create supabase/functions/chunkify/uploads.ts:
import Chunkify from 'npm:@chunkify/chunkify';
import { createClient } from 'npm:@supabase/supabase-js@2';
const maxFileSizeBytes = 1024 * 1024 * 1024;
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
const chunkify = new Chunkify({
projectAccessToken: Deno.env.get('CHUNKIFY_PROJECT_TOKEN'),
});
const supabase = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
);
export async function createChunkifyUpload(req: Request): Promise<Response> {
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
const token = req.headers.get('Authorization')?.replace('Bearer ', '') ?? '';
const { data: { user } } = await supabase.auth.getUser(token);
if (!user) {
return json({ error: 'Sign in to upload a video.' }, 401);
}
const { filename, file_size_bytes: fileSizeBytes } = await req.json();
if (
!Number.isInteger(fileSizeBytes) ||
fileSizeBytes <= 0 ||
fileSizeBytes > maxFileSizeBytes
) {
return json({ error: 'Choose a video up to 1 GiB.' }, 400);
}
const { data: video, error } = await supabase
.from('videos')
.insert({
user_id: user.id,
title: String(filename ?? '').slice(0, 200),
})
.select('id')
.single();
if (error) {
return json({ error: 'Could not create the video.' }, 500);
}
const extension = /\.[a-z0-9]{1,5}$/i.exec(String(filename ?? ''))?.[0].toLowerCase() ?? '';
const upload = await chunkify.uploads.create({
upload_mode: 'auto',
file_size_bytes: fileSizeBytes,
create_asset: true,
storage: {
path: `sources/${user.id}/${video.id}/original${extension}`,
},
metadata: {
VideoID: video.id,
},
});
await supabase
.from('videos')
.update({ upload_id: upload.id })
.eq('id', video.id);
if (upload.upload_mode === 'multipart') {
return json({
upload_mode: upload.upload_mode,
completion_url: upload.completion_url,
expires_at: upload.expires_at,
multipart: upload.multipart,
});
}
return json({
upload_mode: upload.upload_mode,
upload_url: upload.upload_url,
completion_url: upload.completion_url,
expires_at: upload.expires_at,
});
}
function json(body: unknown, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
},
});
}
The function returns only the session fields the uploader needs. Change maxFileSizeBytes to suit your app, and keep it within the file size limit of your Supabase plan. See Setup for the session fields and transfer modes.
Receive webhooks
The /webhook route checks each notification's signature with the Chunkify SDK, then updates the video's row. It finds the row through the VideoID metadata, which Chunkify copies from the Upload to the video asset.
Events can arrive more than once and in any order. The status filters below keep a late event from moving a video back to an earlier status, and repeating an update has no further effect.
Create supabase/functions/chunkify/webhook.ts:
import Chunkify from 'npm:@chunkify/chunkify';
import { createClient } from 'npm:@supabase/supabase-js@2';
const chunkify = new Chunkify({
webhookKey: Deno.env.get('CHUNKIFY_WEBHOOK_SECRET'),
});
const supabase = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
);
export async function handleChunkifyWebhook(req: Request): Promise<Response> {
let notification: Chunkify.UnwrapWebhookEvent;
try {
notification = chunkify.webhooks.unwrap(await req.text(), {
headers: {
'webhook-id': req.headers.get('webhook-id') ?? '',
'webhook-timestamp': req.headers.get('webhook-timestamp') ?? '',
'webhook-signature': req.headers.get('webhook-signature') ?? '',
},
});
} catch {
return new Response('Invalid signature', { status: 400 });
}
switch (notification.event) {
case 'upload.completed': {
const { upload, source } = notification.data;
await updateVideo(
upload.metadata?.VideoID,
{
status: 'processing',
source_id: source.id,
asset_id: upload.asset_id,
},
['uploading'],
);
break;
}
case 'asset.playback_ready': {
const { asset } = notification.data;
await updateVideo(
asset.metadata?.VideoID,
{
status: 'playable',
asset_id: asset.id,
playback_url: asset.cdn_url,
},
['uploading', 'processing'],
);
break;
}
case 'asset.ready': {
const { asset } = notification.data;
await updateVideo(asset.metadata?.VideoID, {
status: 'ready',
asset_id: asset.id,
playback_url: asset.cdn_url,
poster_url: asset.poster?.cdn_url,
thumbnails_url: asset.timeline_previews?.cdn_url,
});
break;
}
case 'asset.failed': {
const { asset } = notification.data;
await updateVideo(asset.metadata?.VideoID, { status: 'failed' });
break;
}
}
return new Response('OK');
}
async function updateVideo(
videoId: string | undefined,
values: Record<string, unknown>,
fromStatuses?: string[],
) {
if (!videoId) {
return;
}
let query = supabase.from('videos').update(values).eq('id', videoId);
if (fromStatuses) {
query = query.in('status', fromStatuses);
}
const { error } = await query;
if (error) {
throw error;
}
}
If the database update fails, the route returns an error and Chunkify sends the notification again. See Webhooks for retries and the full event payloads.
Deploy the function
Chunkify does not send a Supabase access token with its notifications, so deploy the function without Supabase's JWT check. The /webhook route authenticates each request with its signature, and the /uploads route checks the user's access token itself.
supabase functions deploy chunkify --no-verify-jwt
Add the uploader
These examples use the Next.js App Router with the Supabase clients from Supabase's Next.js setup, imported from @/utils/supabase/client and @/utils/supabase/server. Install the Chunkify components:
npm install @chunkify/uploader @chunkify/player-react
Create a client component that calls the /uploads route from the uploader's upload provider. supabase.functions.invoke sends the signed-in user's access token with the request.
'use client';
import {
ChunkifyUploader,
ChunkifyUploaderHeading,
ChunkifyUploaderFileSelect,
ChunkifyUploaderProgressText,
ChunkifyUploaderProgressBar,
ChunkifyUploaderError,
ChunkifyUploaderRetry,
ChunkifyUploaderSuccess,
} from '@chunkify/uploader/react';
import type { UploadSession } from '@chunkify/uploader';
import { createClient } from '@/utils/supabase/client';
const supabase = createClient();
async function createUpload(file: File): Promise<UploadSession> {
const { data, error } = await supabase.functions.invoke('chunkify/uploads', {
body: {
filename: file.name,
file_size_bytes: file.size,
},
});
if (error) {
throw new Error('Could not create an upload session.');
}
return data;
}
export default function VideoUpload() {
return (
<ChunkifyUploader upload={createUpload} drop maxFileSize={1024}>
<ChunkifyUploaderHeading>Drop a video here</ChunkifyUploaderHeading>
<ChunkifyUploaderFileSelect>Select a video</ChunkifyUploaderFileSelect>
<ChunkifyUploaderProgressText />
<ChunkifyUploaderProgressBar />
<ChunkifyUploaderError>Upload failed. Retry or start over.</ChunkifyUploaderError>
<ChunkifyUploaderRetry>Retry</ChunkifyUploaderRetry>
<ChunkifyUploaderSuccess>
Upload complete. Your video appears once it is ready to play.
</ChunkifyUploaderSuccess>
</ChunkifyUploader>
);
}
Show this component only to signed-in users; the /uploads route rejects requests without a Supabase session. Keep maxFileSize in MiB in line with the function's limit. Supabase Storage accepts browser uploads from any origin, so you do not need to set up CORS for the bucket. See Chunkify Uploader to style the component.
Play the videos
Read the videos in a server component. Once a video has a playback_url, play it with Chunkify Player:
import { ChunkifyPlayer } from '@chunkify/player-react';
import { createClient } from '@/utils/supabase/server';
export default async function VideosPage() {
const supabase = await createClient();
const { data: videos } = await supabase
.from('videos')
.select('id, playback_url, poster_url, thumbnails_url')
.not('playback_url', 'is', null)
.order('created_at', { ascending: false });
return (
<ul>
{videos?.map((video) => (
<li key={video.id}>
<ChunkifyPlayer
src={video.playback_url}
poster={video.poster_url ?? undefined}
thumbnails={video.thumbnails_url ?? undefined}
crossOrigin="anonymous"
aspectRatio="landscape"
controls
playsInline
/>
</li>
))}
</ul>
);
}
The stream, poster, and timeline previews load from Supabase's CDN. Your app stores these URLs, so it does not need to call Chunkify when someone watches a video. See Chunkify Player for the player's options.
Things to know
- File size: Supabase limits the size of each uploaded file, and the limit depends on your Supabase plan. Uploads above that limit fail when the browser sends the file.
- S3 access keys: the keys you give Chunkify can read and write every bucket in your Supabase project and bypass row-level security. Only Chunkify's servers use them.
- Delivery costs: viewers stream video from Supabase's CDN, so Supabase bills that traffic under your plan's egress pricing. Chunkify charges for processing and for writing files to your storage. See Data transfer costs.
- Public bucket: anyone with its URL can read an object in the
videosbucket, including the original uploads undersources/. Keep files that must stay private in other buckets.
Add playback analytics
To see views, watch time, and playback quality for these videos, turn on Chunkify Analytics in the player. Add asset_id to the select in VideosPage, then pass the analytics props to each player:
<ChunkifyPlayer
src={video.playback_url}
poster={video.poster_url ?? undefined}
thumbnails={video.thumbnails_url ?? undefined}
crossOrigin="anonymous"
aspectRatio="landscape"
controls
playsInline
analytics
analyticsIngestKey={process.env.NEXT_PUBLIC_CHUNKIFY_PLAYER_KEY}
analyticsVideoId={video.asset_id}
/>
Copy the public Player key from your analytics settings and add your website's origin to its allowed origins, as described in Setup. The Player key only lets players send events, so it can live in browser code. Keep read keys on your server.
Using the Asset ID as the video ID lets the analytics dashboard show each video's title, poster, and timeline thumbnails. See Connect your player for the other options.


