Official TypeScript library providing comprehensive client access to Mux's video infrastructure API including asset management, live streaming, analytics, and webhook handling
Direct upload functionality for secure file transfers to Mux, providing pre-signed URLs and upload tracking with automatic asset creation upon completion.
Create secure, time-limited upload URLs for direct client-side file uploads to Mux.
/**
* Create a direct upload URL
* @param body - Upload creation parameters
* @returns Promise resolving to the created upload configuration
*/
create(body: UploadCreateParams): Promise<Upload>;
interface UploadCreateParams {
/** CORS origin for browser uploads */
cors_origin?: string;
/** Asset settings for the created asset */
new_asset_settings?: NewAssetSettings;
/** Test mode flag */
test?: boolean;
/** Upload timeout in seconds */
timeout?: number;
}
interface Upload {
/** Unique identifier for the Direct Upload */
id: string;
/** CORS origin for browser uploads (required) */
cors_origin: string;
/** Current upload status */
status: 'waiting' | 'asset_created' | 'errored' | 'cancelled' | 'timed_out';
/** Max time in seconds for the signed upload URL to be valid */
timeout: number;
/** Pre-signed URL for uploading the file */
url: string;
/** Asset ID created from successful upload (only set once upload is in 'asset_created' state) */
asset_id?: string;
/** Error information if upload failed (only set if error occurred during asset creation) */
error?: UploadError;
/** Asset settings to apply when creating the asset */
new_asset_settings?: NewAssetSettings;
/** Indicates if this is a test Direct Upload (created asset will be a test asset) */
test?: boolean;
}
interface NewAssetSettings {
/** Playback policies for the created asset */
playback_policies?: Array<PlaybackPolicy>;
/** MP4 support settings */
mp4_support?: Mp4Support;
/** Audio normalization */
normalize_audio?: boolean;
/** Master file access */
master_access?: MasterAccess;
/** Input settings */
inputs?: Array<InputSettings>;
}Usage Examples:
// Basic upload creation
const upload = await mux.video.uploads.create({
cors_origin: "https://myapp.example.com",
new_asset_settings: {
playback_policies: ["public"],
},
});
// Upload with advanced asset settings
const upload = await mux.video.uploads.create({
cors_origin: "https://myapp.example.com",
timeout: 3600, // 1 hour timeout
new_asset_settings: {
playback_policies: ["signed"],
mp4_support: "standard",
normalize_audio: true,
input: [
{
generated_subtitles: [
{
language_code: "en",
name: "English Auto-Generated",
},
],
},
],
},
});
// Client-side upload (example)
const formData = new FormData();
formData.append("file", videoFile);
const response = await fetch(upload.url, {
method: "PUT",
body: videoFile,
headers: {
"Content-Type": videoFile.type,
},
});Monitor and manage upload status and lifecycle.
/**
* Retrieve upload details and status
* @param uploadId - The upload identifier
* @returns Promise resolving to upload details
*/
retrieve(uploadId: string): Promise<Upload>;
/**
* List uploads with optional filtering and pagination
* @param query - Listing parameters
* @returns Paginated list of uploads
*/
list(query?: UploadListParams): PagePromise<UploadsBasePage, Upload>;
interface UploadListParams extends BasePageParams {
/** Filter by upload status */
status?: 'waiting' | 'asset_created' | 'errored' | 'cancelled' | 'timed_out';
}
/**
* Cancel a pending upload
* @param uploadId - The upload identifier
* @returns Promise that resolves when cancellation is complete
*/
cancel(uploadId: string): Promise<void>;Track upload progress and handle completion or failure states.
Upload Lifecycle:
Status Monitoring Example:
// Poll upload status
async function waitForUpload(uploadId: string): Promise<string> {
while (true) {
const upload = await mux.video.uploads.retrieve(uploadId);
switch (upload.status) {
case 'asset_created':
return upload.asset_id!;
case 'errored':
throw new Error(`Upload failed: ${upload.error?.message}`);
case 'cancelled':
throw new Error('Upload was cancelled');
case 'timed_out':
throw new Error('Upload timed out');
case 'waiting':
// Continue polling
await new Promise(resolve => setTimeout(resolve, 1000));
break;
}
}
}
// Usage
const upload = await mux.video.uploads.create({
cors_origin: "https://myapp.example.com",
});
// ... perform client-side upload to upload.url ...
const assetId = await waitForUpload(upload.id);
console.log(`Asset created: ${assetId}`);interface UploadError {
/** Human-readable error message */
message?: string;
/** Label for the specific error */
type?: string;
}Common Upload Errors:
async function uploadVideoFile(
file: File,
uploadUrl: string,
onProgress?: (percent: number) => void
): Promise<void> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
// Track upload progress
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable && onProgress) {
const percent = (event.loaded / event.total) * 100;
onProgress(percent);
}
});
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
} else {
reject(new Error(`Upload failed with status ${xhr.status}`));
}
});
xhr.addEventListener('error', () => {
reject(new Error('Upload failed'));
});
xhr.open('PUT', uploadUrl);
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
});
}
// Usage
const upload = await mux.video.uploads.create({
cors_origin: window.location.origin,
});
await uploadVideoFile(
videoFile,
upload.url,
(percent) => console.log(`Upload ${percent.toFixed(1)}% complete`)
);
const assetId = await waitForUpload(upload.id);import { createReadStream } from 'fs';
import fetch from 'node-fetch';
async function uploadVideoFileNode(
filePath: string,
uploadUrl: string
): Promise<void> {
const fileStream = createReadStream(filePath);
const response = await fetch(uploadUrl, {
method: 'PUT',
body: fileStream,
headers: {
'Content-Type': 'video/mp4', // Set appropriate MIME type
},
});
if (!response.ok) {
throw new Error(`Upload failed with status ${response.status}`);
}
}type PlaybackPolicy = 'public' | 'signed' | 'drm';
type Mp4Support = 'none' | 'standard' | 'capped-1080p';
type MasterAccess = 'temporary' | 'none';
interface InputSettings {
url?: string;
overlay_settings?: OverlaySettings;
generated_subtitles?: Array<GeneratedSubtitleSettings>;
start_time?: number;
end_time?: number;
type?: string;
}
interface GeneratedSubtitleSettings {
language_code?: string;
name?: string;
passthrough?: string;
}
interface OverlaySettings {
vertical_align?: 'top' | 'middle' | 'bottom';
vertical_margin?: string;
horizontal_align?: 'left' | 'center' | 'right';
horizontal_margin?: string;
width?: string;
height?: string;
opacity?: string;
}Install with Tessl CLI
npx tessl i tessl/npm-mux--mux-nodedocs