Skip to Content
Frameworks

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.com

The env file

init writes five variables to .env.local, which Next.js loads on the server:

VariableWhat it is
CLIPMUX_URLThe ClipMux server's public URL.
CLIPMUX_API_KEYYour app's API key, cmx_….
CLIPMUX_SIGNING_KIDThe ID of your app's signing key.
CLIPMUX_SIGNING_KEYThe signing key itself, a PEM.
CLIPMUX_WEBHOOK_SECRETThe 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

app/api/clipmux/[action]/route.ts
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.

  • upload runs when someone chooses a file. Return the upload's settings, or null to refuse with 403.
  • playback runs when someone presses play, and again when the token runs out. Return { viewerId }, or null to refuse.
  • asset runs 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

app/lessons/[id]/video.tsx
'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:

app/lessons/[id]/page.tsx
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 doctor

For 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/webhook

listen 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 upload callback returned null, or threw.
  • /api/clipmux/upload answers with Next.js's own 404 page: the file isn't at app/api/clipmux/[action]/route.ts.
  • listen shows 400: the app reads a different CLIPMUX_WEBHOOK_SECRET from the one listen signs with.

Next

On this page