Mux TypeScript API Library

This library provides convenient access to the Mux REST API from server-side TypeScript or JavaScript.
The REST API documentation can be found on docs.mux.com. The full API of this library can be found in api.md.
Note: As of v14 of mux-node-sdk, we have changed some internal workings of the SDKs. You can read more about this here.
MCP Server
Use the Mux MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.

Note: You may need to set environment variables in your MCP client.
Installation
Usage
The full API of this library can be found in api.md.
import Mux from '@mux/ts';
const client = new Mux({
tokenId: process.env['MUX_TOKEN_ID'], // This is the default and can be omitted
tokenSecret: process.env['MUX_TOKEN_SECRET'], // This is the default and can be omitted
});
const asset = await client.video.assets.create({
inputs: [{ url: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4' }],
playback_policies: ['public'],
});
console.log(asset.id);
Request & Response types
This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:
import Mux from '@mux/ts';
const client = new Mux({
tokenId: process.env['MUX_TOKEN_ID'], // This is the default and can be omitted
tokenSecret: process.env['MUX_TOKEN_SECRET'], // This is the default and can be omitted
});
const params: Mux.Video.AssetCreateParams = {
inputs: [{ url: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4' }],
playback_policies: ['public'],
};
const asset: Mux.Video.Asset = await client.video.assets.create(params);
Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.
You can use any JWT-compatible library, but we've included some light helpers in the SDK to make it easier to get up and running.
// Assuming you have your signing key specified in your environment variables:
// Signing token ID: process.env.MUX_SIGNING_KEY
// Signing token secret: process.env.MUX_PRIVATE_KEY
// Most simple request, defaults to type video and is valid for 7 days.
const token = mux.jwt.signPlaybackId('some-playback-id');
// https://stream.mux.com/some-playback-id.m3u8?token=${token}
// If you wanted to sign a thumbnail
const thumbParams = { time: 14, width: 100 };
const thumbToken = mux.jwt.signPlaybackId('some-playback-id', {
type: 'thumbnail',
params: thumbParams,
});
// https://image.mux.com/some-playback-id/thumbnail.jpg?token=${token}
// If you wanted to sign a gif
const gifToken = mux.jwt.signPlaybackId('some-playback-id', { type: 'gif' });
// https://image.mux.com/some-playback-id/animated.gif?token=${token}
// Here's an example for a storyboard
const storyboardToken = mux.jwt.signPlaybackId('some-playback-id', {
type: 'storyboard',
});
// https://image.mux.com/some-playback-id/storyboard.jpg?token=${token}
// You can also use `signViewerCounts` to get a token
// used for requests to the Mux Engagement Counts API
// https://docs.mux.com/guides/see-how-many-people-are-watching
const statsToken = mux.jwt.signViewerCounts('some-live-stream-id', {
type: 'live_stream',
});
// https://stats.mux.com/counts?token={statsToken}
Signing multiple JWTs at once
In cases you need multiple tokens, like when using Mux Player, things can get unwieldy pretty quickly. For example,
const playbackToken = await mux.jwt.signPlaybackId(id, {
expiration: "1d",
type: "playback"
})
const thumbnailToken = await mux.jwt.signPlaybackId(id, {
expiration: "1d",
type: "thumbnail",
})
const storyboardToken = await mux.jwt.signPlaybackId(id, {
expiration: "1d",
type: "storyboard"
})
const drmToken = await mux.jwt.signPlaybackId(id, {
expiration: "1d",
type: "drm_license"
})
<mux-player
playback-token={playbackToken}
thumbanil-token={thumbnailToken}
storyboard-token={storyboardToken}
drm-token={drmToken}
playbackId={id}
></mux-player>
To simplify this use-case, you can provide multiple types to signPlaybackId to recieve multiple tokens. These tokens are provided in a format that Mux Player can take as props:
// { "playback-token", "thumbnail-token", "storyboard-token", "drm-token" }
const tokens = await mux.jwt.signPlaybackId(id, {
expiration: "1d",
type: ["playback", "thumbnail", "storyboard", "drm_license"]
})
<mux-player
{...tokens}
playbackId={id}
></mux-player>
If you would like to provide params to a single token (e.g., if you would like to have a thumbnail time), you can provide [type, typeParams] instead of type:
const tokens = await mux.jwt.signPlaybackId(id, {
expiration: '1d',
type: ['playback', ['thumbnail', { time: 2 }], 'storyboard', 'drm_license'],
});
Parsing Webhook payloads
To validate that the given payload was sent by Mux and parse the webhook payload for use in your application,
you can use the mux.webhooks.unwrap utility method.
This method accepts a raw body string and a list of headers. As long as you have set your webhookSecret in the
appropriate configuration property when instantiating the library, all webhooks will be verified for authenticity automatically.
The following example shows how you can handle a webhook using a Next.js app directory API route:
// app/api/mux/webhooks/route.ts
import { revalidatePath } from 'next/cache';
import { headers } from 'next/headers';
import Mux from '@mux/ts';
const mux = new Mux({
webhookSecret: process.env.MUX_WEBHOOK_SECRET,
});
export async function POST(request: Request) {
const headersList = headers();
const body = await request.text();
const event = await mux.webhooks.unwrap(body, headersList);
switch (event.type) {
case 'video.live_stream.active':
case 'video.live_stream.idle':
case 'video.live_stream.disabled':
/**
* `event` is now understood to be one of the following types:
*
* | Mux.Webhooks.VideoLiveStreamActiveWebhookEvent
* | Mux.Webhooks.VideoLiveStreamIdleWebhookEvent
* | Mux.Webhooks.VideoLiveStreamDisabledWebhookEvent
*/
if (event.data.id === 'MySpecialTVLiveStreamID') {
revalidatePath('/tv');
}
break;
default:
break;
}
return Response.json({ message: 'ok' });
}
Verifying Webhook Signatures
Verifying Webhook Signatures is optional but encouraged. Learn more in our Webhook Security Guide
/*
If the header is valid, this function will not throw an error and will not return a value.
If the header is invalid, this function will throw one of the following errors:
- new Error(
"The webhook secret must either be set using the env var, MUX_WEBHOOK_SECRET, on the client class, Mux({ webhookSecret: '123' }), or passed to this function",
);
- new Error('Could not find a mux-signature header');
- new Error(
'Webhook body must be passed as the raw JSON string sent from the server (do not parse it first).',
);
- new Error('Unable to extract timestamp and signatures from header')
- new Error('No v1 signatures found');
- new Error('No signatures found matching the expected signature for payload.')
- new Error('Webhook timestamp is too old')
*/