Next.js integration
Add ClipMux uploads, playback and webhooks to a Next.js App Router app with one route file and one client component.
In Next.js, ClipMux is one route handler and one client component. The route handler answers the uploader, the player and ClipMux's webhooks; the component puts the two elements on your page. This is the setup the quickstart walks through, with the details around it.
For a whole app built this way, see
examples/nextjs-lms: a small course site where
instructors upload, enrolled students watch, and anyone else is refused.
Before you start
- A Next.js app with the App Router, on Node 20.19 or later.
- A ClipMux server and its owner to approve your app.
- The packages, and your app connected:
npm i @clipmux/node @clipmux/uploader @clipmux/player
npx @clipmux/node init --server https://video.example.comThe env file
init writes five variables to .env.local, which Next.js loads on the
server:
| Variable | What it is |
|---|---|
CLIPMUX_URL | The ClipMux server's public URL. |
CLIPMUX_API_KEY | Your app's API key, cmx_…. |
CLIPMUX_SIGNING_KID | The ID of your app's signing key. |
CLIPMUX_SIGNING_KEY | The signing key itself, a PEM. |
CLIPMUX_WEBHOOK_SECRET | The webhook secret, whsec_…. |
None has the NEXT_PUBLIC_ prefix, so none reaches the browser. Keep it
that way, and keep .env.local out of git. In production, set the same
five in your host's secret settings.
The route file
import { clipmuxHandler } from '@clipmux/node/handlers'
export const POST = clipmuxHandler({
// Someone wants to upload: say what the upload is, or return null to refuse.
async upload(req, { file }) {
await requireInstructor(req)
const lesson = new URL(req.url).searchParams.get('lesson')
return { passthrough: `lesson_${lesson}`, title: file.name, generate: { subtitles: true } }
},
// Someone wants to watch: say who they are, or return null to refuse.
async playback(req, { playbackId }) {
const user = await getUser(req)
return (await canWatch(user, playbackId)) ? { viewerId: user.id } : null
},
// A verified webhook, with the video re-fetched so it's current.
async asset(asset) {
await db.lesson.update({
where: { ref: asset.passthrough },
data: { status: asset.status, playbackId: asset.playback_ids[0]?.id },
})
},
})The [action] segment makes this one file answer POSTs to
/api/clipmux/upload, /api/clipmux/playback and
/api/clipmux/webhook. requireInstructor, getUser, canWatch and db
stand for your own code.
uploadruns when someone chooses a file. Return the upload's settings, ornullto refuse with403.playbackruns when someone presses play, and again when the token runs out. Return{ viewerId }, ornullto refuse.assetruns for each verified webhook, with the video re-fetched.
A callback you leave out makes its route a 404. See
Receive webhooks for event and onError.
The handler reads the request body itself, so the webhook's raw body reaches it untouched; there's nothing to configure. It uses only Web APIs, so the route also runs on the Edge runtime.
The client component
'use client'
import type {} from '@clipmux/player/react' // JSX types only
import type {} from '@clipmux/uploader/react'
import { useEffect } from 'react'
export function LessonVideo({ lessonId, playbackId }: { lessonId: string; playbackId?: string }) {
// The elements need the DOM, so load them in the browser only.
useEffect(() => {
import('@clipmux/uploader/element')
import('@clipmux/player/element')
}, [])
return (
<>
<clipmux-uploader create-url={`/api/clipmux/upload?lesson=${lessonId}`} />
{playbackId && <clipmux-player playback-id={playbackId} session-url="/api/clipmux/playback" />}
</>
)
}'use client' and the import() inside useEffect keep the elements out
of the server render: they need the DOM, and the player needs Media Source.
The two import type lines add the elements' JSX types without loading
them.
Render it from a server component, which reads the playback ID from your database:
import { LessonVideo } from './video'
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const lesson = await db.lesson.findUnique({ where: { id } })
return <LessonVideo lessonId={id} playbackId={lesson?.playbackId ?? undefined} />
}To react when a viewer is refused, handle clipmux-denied and call
router.refresh() to re-render the page's locked state. See
Add the player.
Content-Security-Policy
If your app sends a Content-Security-Policy, pages with the elements must
allow ClipMux's origins. doctor prints them:
npx @clipmux/node doctorFor each directive (connect-src, media-src, img-src and style-src), it
names the exact origins your server uses.
Add those sources to the directives your app already sets, in
next.config.ts headers or your middleware. connect-src also lists the
storage bucket that upload parts go to, when it isn't the ClipMux server.
Check it works
Run npx @clipmux/node doctor; it ends with ✓ Ready. Then forward
webhooks and upload from the lesson page:
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhooklisten prints ✓ video.asset.ready ast_… → 200 when encoding is done,
and the video plays after a reload.
- The uploader shows an error at once: your
uploadcallback returnednull, or threw. /api/clipmux/uploadanswers with Next.js's own 404 page: the file isn't atapp/api/clipmux/[action]/route.ts.listenshows400: the app reads a differentCLIPMUX_WEBHOOK_SECRETfrom the onelistensigns with.