Mux Video in Next.js + Sanity CMS: Upload & Playback Guide
By Nayan Kyada · · 6 min read
Part of The Sanity + Next.js Guide
Adding Mux video to a Sanity + Next.js project sounds straightforward until you hit the sharp edges: deciding who gets to hold your Mux credentials, signed playback URLs that require a short-lived JWT on every render, and a poster frame that directly affects LCP. Here is a setup that holds up in production.
Installing the Sanity Mux plugin
Start in your Sanity Studio project:
npm install sanity-plugin-mux-inputThen register it in sanity.config.ts:
// sanity.config.ts
import { defineConfig } from 'sanity'
import { muxInput } from 'sanity-plugin-mux-input'
export default defineConfig({
name: 'default',
title: 'My Studio',
projectId: process.env.SANITY_STUDIO_PROJECT_ID!,
dataset: process.env.SANITY_STUDIO_DATASET!,
plugins: [
muxInput({
static_renditions: ['highest'], // downloadable MP4 fallback (replaces the deprecated mp4_support)
}),
],
// ... schema, structure
})The plugin prompts for a Mux Access Token ID and Secret Key the first time it's configured. Those credentials are stored in your dataset as a mux.apiKey document with the ID secrets.mux — a non-root ID so it's only readable by authenticated Studio users, not the public. That is fine for internal studios; if you'd rather keep Mux credentials off the dataset entirely, handle uploads through your own API route (below) instead.
Add a mux.video field to whichever schema needs it:
// schemas/post.ts
import { defineField, defineType } from 'sanity'
export default defineType({
name: 'post',
type: 'document',
fields: [
defineField({ name: 'title', type: 'string' }),
defineField({
name: 'video',
title: 'Video',
type: 'mux.video', // registered by the plugin
}),
],
})The field stores a weak reference to a mux.videoAsset document, which holds the Mux assetId and playbackId. Follow the reference in GROQ — "video": video.asset->{playbackId, assetId} — to get the playback ID you use for the HLS URL and poster image.
Direct-upload workflow and the server-side proxy
By default the plugin uploads from the Studio to Mux using the credentials saved in the dataset. That is fine for a closed studio, but if you want to gate uploads behind your own auth or log asset IDs somewhere, write a Next.js route handler that creates a Mux direct-upload URL and returns it to the client:
// app/api/mux-upload/route.ts
import { NextResponse } from 'next/server'
import Mux from '@mux/mux-node'
const mux = new Mux({
tokenId: process.env.MUX_TOKEN_ID!,
tokenSecret: process.env.MUX_TOKEN_SECRET!,
})
export async function POST() {
const upload = await mux.video.uploads.create({
new_asset_settings: {
playback_policy: ['signed'], // use 'public' if you do not need signed URLs
static_renditions: [{ resolution: 'highest' }],
},
cors_origin: process.env.NEXT_PUBLIC_SITE_URL!,
})
return NextResponse.json({ uploadUrl: upload.url, uploadId: upload.id })
}(Mux now also publishes this SDK as @mux/ts; existing @mux/mux-node installs keep working.)
Your Studio plugin or a custom upload UI calls POST /api/mux-upload, gets back a one-time upload URL, and streams the file there. Mux fires a webhook when the asset is ready; store the resulting playbackId in Sanity via the Management API or just let editors paste it manually if the volume is low.
Serving signed playback URLs from a Next.js RSC
If you created the asset with playback_policy: ['signed'], every HLS and poster URL needs a short-lived JWT. Do this in a React Server Component so the signing key never hits the client bundle:
// app/posts/[slug]/page.tsx
import Mux from '@mux/mux-node'
import MuxPlayer from '@mux/mux-player-react'
const mux = new Mux({
tokenId: process.env.MUX_TOKEN_ID!,
tokenSecret: process.env.MUX_TOKEN_SECRET!,
})
async function signToken(
playbackId: string,
type: 'video' | 'thumbnail',
params?: Record<string, string>,
) {
return mux.jwt.signPlaybackId(playbackId, {
type,
expiration: '12h',
params, // signed thumbnails: options like time/width must live in the token, not the URL
// add keyId / keySecret from MUX_SIGNING_KEY_ID / MUX_SIGNING_PRIVATE_KEY
keyId: process.env.MUX_SIGNING_KEY_ID!,
keySecret: process.env.MUX_SIGNING_PRIVATE_KEY!,
})
}
export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
// ... fetch the Sanity doc for `slug`, get playbackId
const playbackId = 'YOUR_PLAYBACK_ID'
const [videoToken, thumbnailToken] = await Promise.all([
signToken(playbackId, 'video'),
signToken(playbackId, 'thumbnail', {
time: '3',
width: '1280',
height: '720',
fit_mode: 'smartcrop',
}),
])
// With signed URLs, only the token goes in the query string
const posterUrl =
`https://image.mux.com/${playbackId}/thumbnail.webp?token=${thumbnailToken}`
return (
<main>
{/* Preload the poster so it contributes to LCP immediately */}
<link rel="preload" as="image" href={posterUrl} />
<MuxPlayer
playbackId={playbackId}
tokens={{ playback: videoToken, thumbnail: thumbnailToken }}
poster={posterUrl}
streamType="on-demand"
style={{ aspectRatio: '16/9', width: '100%' }}
/>
</main>
)
}Two token types matter here: video for the stream and thumbnail for the poster. Generate both server-side in a single Promise.all to avoid waterfall latency.
Generating the poster image for LCP
The poster frame is almost always your LCP element on a page with a hero video. A few things that move the number:
Pick a specific timestamp. Without one, Mux uses the asset's thumbnail_time if set, otherwise the middle of the video — which may not be a good frame. Pass time=3 or wherever your best composed frame appears (inside the token's params for signed playback).
Request the exact render size. width/height with fit_mode=smartcrop lets Mux crop to the container ratio rather than letterboxing. Pair this with sizes on any surrounding next/image wrapper if you are compositing it.
Preload it. Add <link rel="preload" as="image" href={posterUrl} /> in the RSC return — Next.js will inject it into <head>. This helps LCP because the browser fetches the poster in parallel with the HTML parse rather than waiting for the player to mount.
Use WebP. Mux serves thumbnails as jpg, png, or webp. Swap thumbnail.jpg for thumbnail.webp for a smaller payload at similar quality.
Handling the Mux webhook in production
When an upload finishes processing, Mux posts to a webhook URL you configure in the Mux dashboard. Wire a route handler to receive video.asset.ready events and write the playbackId back to the Sanity document:
// app/api/mux-webhook/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@sanity/client'
import Mux from '@mux/mux-node'
const mux = new Mux() // reads MUX_TOKEN_ID / MUX_TOKEN_SECRET from env
const sanity = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
token: process.env.SANITY_API_WRITE_TOKEN!,
useCdn: false,
apiVersion: '2024-01-01',
})
export async function POST(req: NextRequest) {
const body = await req.text()
// unwrap() verifies the mux-signature header and throws if it's invalid
let event
try {
event = await mux.webhooks.unwrap(body, req.headers, process.env.MUX_WEBHOOK_SECRET!)
} catch {
return new NextResponse('Unauthorized', { status: 401 })
}
if (event.type !== 'video.asset.ready') return NextResponse.json({ ok: true })
const { id: assetId, playback_ids } = event.data
const playbackId = playback_ids?.[0]?.id
if (playbackId) {
// Patch the Sanity document that stores this asset's data
// (look it up via the upload ID -> Sanity doc ID mapping you saved at upload time)
await sanity.patch('SANITY_DOC_ID').set({ assetId, playbackId }).commit()
}
return NextResponse.json({ ok: true })
}Store the Mux uploadId → Sanity _id mapping in a small lookup (a Sanity document of type muxUploadMapping works fine) so the webhook handler knows which document to patch.
What this gets you
With signed tokens generated in an RSC, your Mux credentials never touch the client. With a preloaded WebP poster at a specific timestamp, the hero video frame is in the browser before the player JavaScript even parses — which removes the poster-load waterfall that usually dominates LCP on video-hero pages.
Frequently asked questions
01How do I add a Sanity Studio input that shows a Mux video preview and stores the embed data?
Install `sanity-plugin-mux-input`, register it in `sanity.config.ts` via the `muxInput()` plugin, then add a field with `type: 'mux.video'` to your schema. That gives editors an upload widget with an in-Studio preview player; the field stores a reference to a `mux.videoAsset` document that holds the Mux `assetId` and `playbackId` — see the installation section below for the exact config.
02What Sanity plugin do I use for Mux video hosting?
`sanity-plugin-mux-input` is the standard one — it adds a `mux.video` field type with a direct-upload widget and in-Studio preview. If you need to gate uploads behind your own auth or logging, you can add your own Next.js route handler that creates Mux direct-upload URLs server-side, so Mux credentials stay on the server.
03How do I serve a Sanity + Mux video with signed playback URLs?
Sign both the video and thumbnail JWTs server-side in a React Server Component using `mux.jwt.signPlaybackId()` — one call with `type: 'video'` for the stream, one with `type: 'thumbnail'` for the poster (thumbnail options like `time` and `width` go inside the token's `params`) — and pass both tokens to `<MuxPlayer>`. Signing in an RSC keeps your Mux signing key out of the client bundle entirely.