Add video upload and streaming to a Next.js app
Let users upload videos from the browser, learn when each one is playable through a webhook, and play it as adaptive HLS in a Next.js App Router app.
By the Chunkify team
This guide adds video upload and playback to an existing Next.js App Router app. Your users pick a file in the browser, Chunkify prepares it as an adaptive HLS stream, and your app saves the playback URL when a webhook says the video can play.
You need a Next.js app with a database, a Chunkify Project, and a Project access token. You can test everything on Chunkify temporary storage before you connect your own bucket and CDN.
What you will build
- A route handler that creates an Upload session with the Chunkify TypeScript SDK.
- A client component that uploads the file with Chunkify Uploader.
- A webhook route handler that verifies each notification and saves the playback URL, poster, and timeline previews.
- A player component that reads those saved URLs.
The flow goes like this. The browser asks your Next.js server for an Upload session. Your server creates it with your Project token and returns only the fields the uploader needs. The uploader sends the file directly to storage and confirms completion with Chunkify. Chunkify creates a Source and a video asset, then prepares the stream. When the initial HLS stream can play, Chunkify sends asset.playback_ready to your webhook. Your handler saves the URLs on your video record, and your page plays them from your own database.
Let a coding agent do it
If you work with a coding agent, the Chunkify skill guides it through the same integration in your codebase. Install it from https://chunkify.dev/SKILL.md, connect the agent to your Project, then describe what you want:
Use the Chunkify skill to add video uploads and on-demand playback to this application. Use my Project's configured storage and CDN, and keep the existing UI and authorization. Handle playback readiness through verified webhooks and save playback URLs with our video records.
The linked page has the installation prompts for Codex and Claude Code. The rest of this guide does the work by hand.
Install the packages
npm install @chunkify/chunkify @chunkify/uploader @chunkify/player-react
@chunkify/chunkify is the server SDK. @chunkify/uploader and @chunkify/player-react run in the browser. The React player wrapper supports React 19; for other versions, use the @chunkify/player web component described in the player guide.
Set the environment variables
In the Chunkify app, open your Project and go to Developers → API tokens. Select New Access Token and copy the token, which starts with sk_project_.
Add it to .env.local with a placeholder for the webhook secret you will create later:
CHUNKIFY_PROJECT_TOKEN=
CHUNKIFY_WEBHOOK_SECRET=
Do not prefix these names with NEXT_PUBLIC_. Next.js exposes variables with that prefix to the browser, and both values must stay on your server.
Decide what to store
Your app plays videos from its own database, so add these fields to your video table or to a new one:
| Field | Purpose |
|---|---|
upload_id |
Chunkify Upload ID, to correlate webhook events. |
asset_id |
Chunkify video asset ID, for later lifecycle events. |
status |
Your own state, such as uploading, playable, ready, or failed. |
playback_url |
HLS master playlist URL for the player. |
poster_url |
Image shown before playback. |
thumbnails_url |
WebVTT file for timeline previews. |
The field names describe a role, not a storage type: they hold test URLs today and CDN URLs once you connect your own storage. The WebVTT file references the preview images, so you do not need a row per thumbnail.
The code below calls createVideo, updateVideo, and getVideo from @/lib/videos. Those stand for your own data layer; implement them with the ORM or query builder your app already uses.
Create the Upload session on your server
Add a route handler at app/api/uploads/route.ts. It creates your video record, asks Chunkify for an Upload session, and returns the session fields to the browser.
// app/api/uploads/route.ts
import Chunkify from '@chunkify/chunkify';
import { createVideo, updateVideo } from '@/lib/videos';
const client = new Chunkify({
projectAccessToken: process.env.CHUNKIFY_PROJECT_TOKEN,
});
export async function POST(request: Request) {
// Authorization boundary: check here, with your app's own auth, that the
// current user is signed in and allowed to upload a video.
const { filename, file_size_bytes } = await request.json();
if (!Number.isInteger(file_size_bytes) || file_size_bytes <= 0) {
return Response.json({ error: 'Invalid file size' }, { status: 400 });
}
// Create your record first so a webhook can always find it.
const video = await createVideo({ title: filename, status: 'uploading' });
const upload = await client.uploads.create({
upload_mode: 'auto',
file_size_bytes,
create_asset: true,
metadata: {
VideoID: video.id,
},
});
await updateVideo(video.id, { upload_id: upload.id });
const session = upload.upload_mode === 'multipart'
? {
upload_mode: upload.upload_mode,
completion_url: upload.completion_url,
expires_at: upload.expires_at,
multipart: upload.multipart,
}
: {
upload_mode: upload.upload_mode,
upload_url: upload.upload_url,
completion_url: upload.completion_url,
expires_at: upload.expires_at,
};
return Response.json(session, {
headers: { 'Cache-Control': 'no-store' },
});
}
create_asset: trueasks Chunkify to prepare a video asset for streaming once the upload completes. Without it, you only get a Source.upload_mode: 'auto'uses a single PUT at or below 100 MiB and multipart above it. Always send the selected file's exact size.- Chunkify copies Upload metadata to the Source and the video asset.
VideoIDis how the webhook handler finds your record. Metadata values are strings, so convert a numeric ID. - The response contains only the session fields the uploader needs, returned directly without a wrapper. The Project token never leaves the server.
This request has no storage field, so the original goes to Chunkify temporary storage. Going to production shows the change for your own bucket.
Add the uploader
Chunkify Uploader handles file selection, drag and drop, progress, retries, and completion. You give it a function that requests a session from your route; it calls that function after a file is selected.
The uploader is a set of web components, so it belongs in a client component. Create components/video-upload.tsx:
// components/video-upload.tsx
'use client';
import {
ChunkifyUploader,
ChunkifyUploaderHeading,
ChunkifyUploaderFileSelect,
ChunkifyUploaderProgressText,
ChunkifyUploaderProgressBar,
ChunkifyUploaderError,
ChunkifyUploaderRetry,
ChunkifyUploaderSuccess,
} from '@chunkify/uploader/react';
async function createUpload(file: File) {
const response = await fetch('/api/uploads', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: file.name,
file_size_bytes: file.size,
}),
});
if (!response.ok) throw new Error('Could not create an upload session.');
return response.json();
}
export default function VideoUpload() {
return (
<ChunkifyUploader
className="video-upload"
upload={createUpload}
drop
maxFileSize={1024}
onUploadSuccess={(event) => {
console.log('Upload complete:', event.detail.file.name);
}}
>
<ChunkifyUploaderHeading>Drop a video here</ChunkifyUploaderHeading>
<ChunkifyUploaderFileSelect className="upload-button">
Select a video
</ChunkifyUploaderFileSelect>
<ChunkifyUploaderProgressText />
<ChunkifyUploaderProgressBar />
<ChunkifyUploaderError>Upload failed. Retry or start over.</ChunkifyUploaderError>
<ChunkifyUploaderRetry className="upload-button">Retry</ChunkifyUploaderRetry>
<ChunkifyUploaderSuccess>Upload complete!</ChunkifyUploaderSuccess>
</ChunkifyUploader>
);
}
Render <VideoUpload /> from any page. maxFileSize is in MiB; omit it to remove the component's limit. Your plan's limits still apply.
onUploadSuccess means Chunkify confirmed the upload and created the Source. It does not mean the video can play yet, and the event carries no Source or video asset ID. That information reaches your server through the webhook.
See Styles to match the component to your app and Events for progress and error callbacks.
Handle the webhook
Chunkify notifies your server as the video moves through processing. For this flow, handle four events:
| Event | What to do |
|---|---|
upload.completed |
Save data.upload.asset_id on your record. |
asset.playback_ready |
Save the playback URL. The initial HLS stream can play. |
asset.ready |
Save the poster and timeline preview URLs. |
asset.failed |
Mark the video as failed. |
Create the handler at app/api/webhooks/chunkify/route.ts:
// app/api/webhooks/chunkify/route.ts
import Chunkify from '@chunkify/chunkify';
import { updateVideo } from '@/lib/videos';
const client = new Chunkify({
webhookKey: process.env.CHUNKIFY_WEBHOOK_SECRET,
});
export async function POST(request: Request) {
// Read the body as text. Parsing it first changes the bytes
// and makes signature verification fail.
const rawBody = await request.text();
const headers = {
'webhook-id': request.headers.get('webhook-id') ?? '',
'webhook-timestamp': request.headers.get('webhook-timestamp') ?? '',
'webhook-signature': request.headers.get('webhook-signature') ?? '',
};
let notification: Chunkify.UnwrapWebhookEvent;
try {
notification = client.webhooks.unwrap(rawBody, { headers });
} catch {
return new Response('Invalid webhook', { status: 400 });
}
switch (notification.event) {
case 'upload.completed': {
const { upload } = notification.data;
const videoId = upload.metadata?.VideoID;
if (videoId && upload.asset_id) {
await updateVideo(videoId, { asset_id: upload.asset_id });
}
break;
}
case 'asset.playback_ready':
case 'asset.ready': {
const { asset } = notification.data;
const videoId = asset.metadata?.VideoID;
if (!videoId) break;
// Prefer your CDN. Fall back to the public preview while testing.
const playbackUrl = asset.cdn_url || asset.preview_url;
const posterUrl = asset.poster?.cdn_url || asset.poster?.preview_url;
const thumbnailsUrl =
asset.timeline_previews?.cdn_url || asset.timeline_previews?.preview_url;
await updateVideo(videoId, {
asset_id: asset.id,
status: asset.status === 'ready' ? 'ready' : 'playable',
...(playbackUrl && { playback_url: playbackUrl }),
...(posterUrl && { poster_url: posterUrl }),
...(thumbnailsUrl && { thumbnails_url: thumbnailsUrl }),
});
break;
}
case 'asset.failed': {
const { asset } = notification.data;
const videoId = asset.metadata?.VideoID;
if (videoId) await updateVideo(videoId, { status: 'failed' });
break;
}
}
return new Response('OK', { status: 200 });
}
client.webhooks.unwrap verifies the signature and returns the typed notification. It throws when the signature does not match, so nothing below it runs for a forged request.
In a route handler, await request.text() gives you the body exactly as received. Do not call request.json() first. If your app has auth middleware, let this path through: the signature is what authenticates the request.
Chunkify retries failed deliveries, and the browser's success event and server notifications can arrive in either order. The handler above only writes fields that are present, so running it twice for the same event leaves the record unchanged. Make sure updateVideo cannot move a ready video back to playable if an older notification arrives late.
Register the webhook
In your Project, open Developers → Webhooks → Setup webhook. Enter your deployed route's URL, such as https://app.example.com/api/webhooks/chunkify, and select the four events above. Select asset.playback_ready explicitly. Copy the Webhook secret into CHUNKIFY_WEBHOOK_SECRET.
Chunkify cannot reach a development server on your machine. For local testing, the Chunkify CLI's chunkify listen command creates a temporary webhook and forwards notifications to a local URL. See Receive webhook notifications locally.
Play the video
ChunkifyPlayer takes the three saved URLs. The wrapper is safe to import during server rendering and renders the player after mounting in the browser. Put it in a client component so you can add event handlers later:
// components/video-player.tsx
'use client';
import { ChunkifyPlayer } from '@chunkify/player-react';
type Props = {
playbackUrl: string;
posterUrl?: string | null;
thumbnailsUrl?: string | null;
};
export default function VideoPlayer({ playbackUrl, posterUrl, thumbnailsUrl }: Props) {
return (
<ChunkifyPlayer
src={playbackUrl}
poster={posterUrl ?? undefined}
thumbnails={thumbnailsUrl ?? undefined}
crossOrigin="anonymous"
aspectRatio="landscape"
controls
playsInline
/>
);
}
Then read your record in a server component and show the player once a playback URL exists:
// app/videos/[id]/page.tsx
import { notFound } from 'next/navigation';
import VideoPlayer from '@/components/video-player';
import { getVideo } from '@/lib/videos';
export default async function VideoPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
// Authorization boundary: check here that the current user may view this video.
const video = await getVideo(id);
if (!video) notFound();
if (video.status === 'failed') return <p>This video could not be processed.</p>;
if (!video.playback_url) return <p>Your video is being prepared.</p>;
return (
<VideoPlayer
playbackUrl={video.playback_url}
posterUrl={video.poster_url}
thumbnailsUrl={video.thumbnails_url}
/>
);
}
Playback can start at asset.playback_ready, while the video asset is still preparing. The poster and timeline previews may arrive later with asset.ready. Chunkify chooses the renditions for each video from its content, so you do not pick resolutions or bitrates. It uploads the initial stream to storage while it is still encoding, which is why playback can start before processing finishes. Viewers watch that stream first; Chunkify transcodes the other HLS renditions when the player first requests them, and the playback URL stays the same.
Going to production
Connect your storage and CDN
Chunkify temporary storage is for testing. Files stored there are deleted after 24 hours, and the preview_url is a public URL meant for testing. A video saved from a test upload stops playing after that, so do not treat those URLs as permanent.
For production, connect your own storage: Amazon S3, Cloudflare R2, or another S3-compatible provider. You control the bucket and how long files are kept. Then configure a CDN for the bucket and add its base URL to the storage connection. Once that is in place, the video asset has a cdn_url, and the webhook handler above saves it into the same playback_url field.
With your storage as the Project default, choose where each original goes by adding storage.path to the Upload request. Use a unique object key that includes the filename, and build it on your server:
const upload = await client.uploads.create({
upload_mode: 'auto',
file_size_bytes,
create_asset: true,
storage: {
path: `incoming/${video.id}/original.mp4`,
},
metadata: {
VideoID: video.id,
},
});
If you expose a bucket through a public domain, every object in it can be public, including originals stored there. CDN delivery explains how to keep sources private.
Configure CORS
With your own storage, the browser talks to your bucket and CDN directly, so both need CORS rules for your app's origins:
- Uploads: allow
PUTand theContent-Typeheader from every origin that hosts the uploader. Expose theETagresponse header, which multipart uploads need to complete. - Playback: allow
GETandHEADand theRangerequest header on the CDN that serves the stream, poster, and timeline previews.
S3-style CORS updates replace the whole policy, so read the current one and merge your rule into it. Configure CORS has a complete example policy. Test an upload and a playback from each origin you use, including http://localhost:3000 if you develop against the same bucket.
Handle failures and expiry
Upload sessions expire. Single-PUT sessions default to two hours, and multipart sessions to between two and 48 hours depending on file size. A browser error does not always mean the upload failed on Chunkify's side, so rely on webhooks to settle the record's state. Subscribe to upload.failed and upload.expired if you want to clean up records for uploads that never finished.
What it costs
Chunkify bills streaming preparation once per video, by the original's duration and resolution. An HD input, up to 1920 × 1080, costs $0.03 per input minute on Pay as you go and $0.02 on Team, so a 10-minute 1080p upload costs $0.30 or $0.20. All automatic HLS quality levels, the poster, and the timeline previews are included, and more views do not repeat the charge. Your storage and CDN providers bill storage and delivery to viewers themselves. Transferring outputs to Amazon S3 is free; transfers to Cloudflare R2 or other S3-compatible storage use a monthly allowance, then cost $0.09 per GiB. New accounts receive $10 in welcome credit on Pay as you go after verifying a card. See pricing for plans and the streaming pricing reference for every rate.
Frequently asked questions
Can I use the Pages Router?
Yes. Nothing here depends on the App Router except where the files live. You need one server route that creates the Upload session with the SDK and one that receives the webhook. The webhook route must verify the raw request body, so turn off the Pages Router's default body parsing for that API route and read the body as a string before calling unwrap. The uploader and player components work the same way.
Do I need my own S3 bucket to start?
No. A Project can use Chunkify temporary storage for uploads and outputs, and you can play the video through its preview_url when public preview is enabled in Video streaming → Settings. Those files are deleted after 24 hours. Connect your own bucket and CDN before you keep videos for real users.
How do I play the video without the Chunkify player?
The playback URL is an HLS master playlist, and it works with any player that supports HLS. Pass the saved playback_url to your player's HLS source and use its own options for the poster and thumbnails.
Next steps
- Create your first video stream covers the same playback flow from a hosted video URL.
- Chunkify Uploader documents session fields, retries, events, and styling.
- Chunkify Player covers playback options, captions, and events.
- Webhooks lists every event and shows how to resend a notification.
- Workflows add captions, translations, and static MP4 renditions to new videos.
- Storage and delivery explains storage connections, output paths, and CDN setup.