API Routes with the Mux Node SDK
All API requests against the Mux API can be made securely from your application’s backend using the Mux Node SDK inside Next API Routes in pages/api.
Configure environment variables with your Mux API keys: process.env.MUX_TOKEN_ID & process.env.MUX_TOKEN_SECRET.
pages/api/upload.ts
import { NextApiRequest, NextApiResponse } from 'next';
import Mux from '@mux/mux-node';
const { Video } = new Mux();
export default async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const { method } = req;
switch (method) {
case 'POST':
try {
const upload = await Video.Uploads.create({
new_asset_settings: { playback_policy: 'public' },
cors_origin: '*',
});
res.json({
id: upload.id,
url: upload.url,
});
} catch (e) {
res.json({ error: 'Error creating upload' });
}
break;
default:
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${method} Not Allowed`);
}
};
Use Next.js API Routes to listen for Mux webhooks.
pages/api/mux-webhook.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default async function muxWebhookHandler (req: NextApiRequest, res: NextApiResponse): Promise<void> {
const { method, body } = req;
switch (method) {
case 'POST': {
const { data, type } = body;
if (type === 'video.asset.ready') {
/* mark your asset as ready */
} else {
/* handle other event types */
}
res.json({ message: ok });
} default:
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}
Video Playback with <MuxPlayer />
One line of code gives you a fully-featured video player. Integrated with Mux Data out of the box:
jsx
import MuxPlayer from '@mux/mux-player-react'
<MuxPlayer playbackId={playbackId} />
Take advantage of Next.js for a great loading experience.
jsx
import muxBlurHash from '@mux/blurhash'
import MuxPlayer from '@mux/mux-player-react/lazy'
export default function Page({ playbackId, sourceWidth, sourceHeight, blurHashBase64 }) {
return <MuxPlayer
playbackId={playbackId}
style={{ aspectRatio: `${sourceWidth}/${sourceHeight}` }}
placeholder={blurHashBase64}
/>
}
export async function getServerSideProps({ params }) {
const playbackId = params.playbackId
const { sourceWidth, sourceHeight, blurHashBase64 } = await muxBlurHash(playbackId)
return { props: { playbackId, sourceWidth, sourceHeight, blurHashBase64 } }
}