Official TypeScript library providing comprehensive client access to Mux's video infrastructure API including asset management, live streaming, analytics, and webhook handling
The official TypeScript library for the Mux API, providing comprehensive access to Mux's video infrastructure platform including video asset management, live streaming, analytics, webhooks, and JWT signing utilities.
npm install @mux/mux-nodeimport Mux from '@mux/mux-node';For CommonJS:
const Mux = require('@mux/mux-node').default;import Mux from '@mux/mux-node';
// Initialize the client
const client = new Mux({
tokenId: 'YOUR_TOKEN_ID',
tokenSecret: 'YOUR_TOKEN_SECRET',
});
// Create a video asset
const asset = await client.video.assets.create({
inputs: [{ url: 'https://example.com/video.mp4' }],
playback_policies: ['public'],
});
// Get the playback URL
const playbackId = asset.playback_ids[0].id;
const hlsUrl = `https://stream.mux.com/${playbackId}.m3u8`;
// List video views from analytics
const views = await client.data.videoViews.list({
filters: ['asset_id:' + asset.id],
timeframe: ['7:days'],
});The Mux SDK is organized into five major modules, each handling a distinct area of the Mux platform:
All API methods follow consistent patterns with promise-based async/await, automatic pagination for list endpoints, comprehensive TypeScript types, and robust error handling.
The main Mux client provides authentication and configuration for all API operations.
class Mux {
constructor(options?: ClientOptions);
video: Video;
data: Data;
system: System;
webhooks: Webhooks;
jwt: Jwt;
}
interface ClientOptions {
/** API token ID (defaults to process.env.MUX_TOKEN_ID) */
tokenId?: string | null;
/** API token secret (defaults to process.env.MUX_TOKEN_SECRET) */
tokenSecret?: string | null;
/** Webhook verification secret (defaults to process.env.MUX_WEBHOOK_SECRET) */
webhookSecret?: string | null;
/** JWT signing key ID (defaults to process.env.MUX_SIGNING_KEY) */
jwtSigningKey?: string | null;
/** JWT signing private key (defaults to process.env.MUX_PRIVATE_KEY) */
jwtPrivateKey?: string | null;
/** Authorization bearer token (defaults to process.env.MUX_AUTHORIZATION_TOKEN) */
authorizationToken?: string | null;
/** Override base URL (defaults to https://api.mux.com) */
baseURL?: string;
/** Request timeout in milliseconds (default: 60000) */
timeout?: number;
/** Custom HTTP agent */
httpAgent?: Agent;
/** Custom fetch implementation */
fetch?: Function;
/** Maximum retry attempts (default: 2) */
maxRetries?: number;
/** Default headers for all requests */
defaultHeaders?: Headers;
/** Default query parameters for all requests */
defaultQuery?: object;
}Comprehensive video management including VOD assets, live streaming, direct uploads, playback controls, DRM configuration, and delivery utilities.
interface Video {
assets: Assets;
liveStreams: LiveStreams;
uploads: Uploads;
playbackIds: PlaybackIDs;
playbackRestrictions: PlaybackRestrictions;
transcriptionVocabularies: TranscriptionVocabularies;
webInputs: WebInputs;
drmConfigurations: DRMConfigurations;
playback: Playback;
deliveryUsage: DeliveryUsage;
}Query analytics data, metrics, real-time statistics, video views, incidents, and export capabilities for monitoring video performance and viewer behavior.
interface Data {
dimensions: Dimensions;
monitoring: Monitoring;
errors: Errors;
exports: Exports;
filters: Filters;
incidents: Incidents;
metrics: Metrics;
realTime: RealTime;
videoViews: VideoViews;
annotations: Annotations;
}System-level utilities including JWT signing key management and account information retrieval.
interface System {
signingKeys: SigningKeys;
utilities: Utilities;
}Webhook signature verification and event payload parsing to securely process Mux webhook notifications.
interface Webhooks {
/**
* Verify webhook signature to ensure payload authenticity
* @throws Error if signature is invalid or timestamp is too old
*/
verifySignature(body: string, headers: HeadersLike, secret?: string): void;
/**
* Verify signature and parse webhook payload
* @returns Parsed webhook event with normalized timestamps
*/
unwrap(body: string, headers: HeadersLike, secret?: string): UnwrapWebhookEvent;
}
type HeadersLike = Headers | Record<string, string | string[]>;Generate JWT tokens for secure playback, DRM license acquisition, and signed statistics requests.
interface Jwt {
/**
* Create a JWT token for signed playback ID
*/
signPlaybackId(
playbackId: string,
config?: MuxJWTSignOptions
): Promise<string>;
/**
* Create multiple JWT tokens for different media types
*/
signPlaybackId(
playbackId: string,
config?: MuxJWTSignOptionsMultiple
): Promise<Tokens>;
/**
* Create a JWT token for DRM license acquisition
*/
signDrmLicense(
playbackId: string,
config?: MuxJWTSignOptions
): Promise<string>;
/**
* Create a JWT token for signed statistics request
*/
signViewerCounts(
id: string,
config?: MuxJWTSignOptions
): Promise<string>;
}
interface MuxJWTSignOptions {
/** Token type (e.g., 'video', 'thumbnail', 'gif', 'storyboard', 'drm_license') */
type?: string;
/** Token expiration (e.g., '7d', '1h', '30m') - default: '7d' */
expiration?: string;
/** Additional JWT claims */
params?: object;
/** Signing key ID (overrides client.jwtSigningKey) */
keyId?: string;
/** Private key (overrides client.jwtPrivateKey) */
keySecret?: string;
}
interface Tokens {
video?: string;
thumbnail?: string;
gif?: string;
storyboard?: string;
}The SDK provides comprehensive error classes for handling API errors.
class MuxError extends Error {}
class APIError<TStatus, THeaders, TError> extends MuxError {
status: TStatus;
headers: THeaders;
error: TError;
}
class APIUserAbortError extends APIError {}
class APIConnectionError extends APIError {}
class APIConnectionTimeoutError extends APIConnectionError {}
class BadRequestError extends APIError {}
class AuthenticationError extends APIError {}
class PermissionDeniedError extends APIError {}
class NotFoundError extends APIError {}
class ConflictError extends APIError {}
class UnprocessableEntityError extends APIError {}
class RateLimitError extends APIError {}
class InternalServerError extends APIError {}List endpoints return paginated responses with iteration support.
class PageWithTotal<Item> {
data: Array<Item>;
total_row_count: number;
timeframe: Array<number>;
limit: number;
getPaginatedItems(): Array<Item>;
nextPageInfo(): PageInfo | null;
/** @deprecated Use nextPageInfo() instead */
nextPageParams(): Partial<PageWithTotalParams> | null;
}
class BasePage<Item> {
data: Array<Item>;
getPaginatedItems(): Array<Item>;
nextPageInfo(): PageInfo | null;
/** @deprecated Use nextPageInfo() instead */
nextPageParams(): Partial<BasePageParams> | null;
}
interface PageInfo {
params?: Record<string, any>;
url?: URL;
}Helper functions for creating file uploads.
/**
* Create a File object from various data formats
*/
async function toFile(
value: ToFileInput | PromiseLike<ToFileInput>,
name?: string | null,
options?: FilePropertyBag
): Promise<FileLike>;
/**
* Create a File from a file system path (Node.js only)
*/
function fileFromPath(path: string): Promise<FileLike>;
type ToFileInput = Uploadable | BlobLikePart | AsyncIterable<BlobLikePart>;
type Uploadable = FileLike | ResponseLike | FsReadStream;
interface FileLike {
name: string;
lastModified: number;
size: number;
type: string;
text(): Promise<string>;
slice(start?: number, end?: number): FileLike;
}interface PlaybackID {
/** Unique identifier for the PlaybackID */
id: string;
/** Access control policy */
policy: PlaybackPolicy;
/** DRM configuration ID (required when policy is 'drm') */
drm_configuration_id?: string;
}
type PlaybackPolicy = 'public' | 'signed' | 'drm';Install with Tessl CLI
npx tessl i tessl/npm-mux--mux-nodedocs