or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analytics-metrics.mdclient-setup.mddata.mddelivery-usage.mderror-handling.mdindex.mdjwt-signing.mdjwt.mdlive-streaming.mdplayback-control.mdsystem-operations.mdsystem.mdtranscription-vocabularies.mdupload-utilities.mdvideo-assets.mdvideo-playback.mdvideo-uploads.mdvideo.mdweb-inputs.mdwebhooks.md

index.mddocs/

0

# Mux Node SDK

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: @mux/mux-node

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @mux/mux-node`

10

11

## Core Imports

12

13

```typescript

14

import Mux from '@mux/mux-node';

15

```

16

17

For CommonJS:

18

19

```javascript

20

const Mux = require('@mux/mux-node').default;

21

```

22

23

## Basic Usage

24

25

```typescript

26

import Mux from '@mux/mux-node';

27

28

// Initialize the client

29

const client = new Mux({

30

tokenId: 'YOUR_TOKEN_ID',

31

tokenSecret: 'YOUR_TOKEN_SECRET',

32

});

33

34

// Create a video asset

35

const asset = await client.video.assets.create({

36

inputs: [{ url: 'https://example.com/video.mp4' }],

37

playback_policies: ['public'],

38

});

39

40

// Get the playback URL

41

const playbackId = asset.playback_ids[0].id;

42

const hlsUrl = `https://stream.mux.com/${playbackId}.m3u8`;

43

44

// List video views from analytics

45

const views = await client.data.videoViews.list({

46

filters: ['asset_id:' + asset.id],

47

timeframe: ['7:days'],

48

});

49

```

50

51

## Architecture

52

53

The Mux SDK is organized into five major modules, each handling a distinct area of the Mux platform:

54

55

- **Video Module**: Video asset management, live streaming, uploads, playback IDs, DRM, and delivery utilities

56

- **Data Module**: Analytics, metrics, real-time data, video views, incidents, and data exports

57

- **System Module**: Signing keys management and account utilities

58

- **Webhooks Module**: Webhook signature verification and event payload parsing

59

- **JWT Module**: JWT token signing for secure playback, DRM licenses, and viewer counts

60

61

All API methods follow consistent patterns with promise-based async/await, automatic pagination for list endpoints, comprehensive TypeScript types, and robust error handling.

62

63

## Capabilities

64

65

### Client Initialization

66

67

The main Mux client provides authentication and configuration for all API operations.

68

69

```typescript { .api }

70

class Mux {

71

constructor(options?: ClientOptions);

72

73

video: Video;

74

data: Data;

75

system: System;

76

webhooks: Webhooks;

77

jwt: Jwt;

78

}

79

80

interface ClientOptions {

81

/** API token ID (defaults to process.env.MUX_TOKEN_ID) */

82

tokenId?: string | null;

83

/** API token secret (defaults to process.env.MUX_TOKEN_SECRET) */

84

tokenSecret?: string | null;

85

/** Webhook verification secret (defaults to process.env.MUX_WEBHOOK_SECRET) */

86

webhookSecret?: string | null;

87

/** JWT signing key ID (defaults to process.env.MUX_SIGNING_KEY) */

88

jwtSigningKey?: string | null;

89

/** JWT signing private key (defaults to process.env.MUX_PRIVATE_KEY) */

90

jwtPrivateKey?: string | null;

91

/** Authorization bearer token (defaults to process.env.MUX_AUTHORIZATION_TOKEN) */

92

authorizationToken?: string | null;

93

/** Override base URL (defaults to https://api.mux.com) */

94

baseURL?: string;

95

/** Request timeout in milliseconds (default: 60000) */

96

timeout?: number;

97

/** Custom HTTP agent */

98

httpAgent?: Agent;

99

/** Custom fetch implementation */

100

fetch?: Function;

101

/** Maximum retry attempts (default: 2) */

102

maxRetries?: number;

103

/** Default headers for all requests */

104

defaultHeaders?: Headers;

105

/** Default query parameters for all requests */

106

defaultQuery?: object;

107

}

108

```

109

110

### Video Operations

111

112

Comprehensive video management including VOD assets, live streaming, direct uploads, playback controls, DRM configuration, and delivery utilities.

113

114

```typescript { .api }

115

interface Video {

116

assets: Assets;

117

liveStreams: LiveStreams;

118

uploads: Uploads;

119

playbackIds: PlaybackIDs;

120

playbackRestrictions: PlaybackRestrictions;

121

transcriptionVocabularies: TranscriptionVocabularies;

122

webInputs: WebInputs;

123

drmConfigurations: DRMConfigurations;

124

playback: Playback;

125

deliveryUsage: DeliveryUsage;

126

}

127

```

128

129

[Video Module Documentation](./video.md)

130

131

### Data Analytics

132

133

Query analytics data, metrics, real-time statistics, video views, incidents, and export capabilities for monitoring video performance and viewer behavior.

134

135

```typescript { .api }

136

interface Data {

137

dimensions: Dimensions;

138

monitoring: Monitoring;

139

errors: Errors;

140

exports: Exports;

141

filters: Filters;

142

incidents: Incidents;

143

metrics: Metrics;

144

realTime: RealTime;

145

videoViews: VideoViews;

146

annotations: Annotations;

147

}

148

```

149

150

[Data Module Documentation](./data.md)

151

152

### System Management

153

154

System-level utilities including JWT signing key management and account information retrieval.

155

156

```typescript { .api }

157

interface System {

158

signingKeys: SigningKeys;

159

utilities: Utilities;

160

}

161

```

162

163

[System Module Documentation](./system.md)

164

165

### Webhook Handling

166

167

Webhook signature verification and event payload parsing to securely process Mux webhook notifications.

168

169

```typescript { .api }

170

interface Webhooks {

171

/**

172

* Verify webhook signature to ensure payload authenticity

173

* @throws Error if signature is invalid or timestamp is too old

174

*/

175

verifySignature(body: string, headers: HeadersLike, secret?: string): void;

176

177

/**

178

* Verify signature and parse webhook payload

179

* @returns Parsed webhook event with normalized timestamps

180

*/

181

unwrap(body: string, headers: HeadersLike, secret?: string): UnwrapWebhookEvent;

182

}

183

184

type HeadersLike = Headers | Record<string, string | string[]>;

185

```

186

187

[Webhooks Module Documentation](./webhooks.md)

188

189

### JWT Token Signing

190

191

Generate JWT tokens for secure playback, DRM license acquisition, and signed statistics requests.

192

193

```typescript { .api }

194

interface Jwt {

195

/**

196

* Create a JWT token for signed playback ID

197

*/

198

signPlaybackId(

199

playbackId: string,

200

config?: MuxJWTSignOptions

201

): Promise<string>;

202

203

/**

204

* Create multiple JWT tokens for different media types

205

*/

206

signPlaybackId(

207

playbackId: string,

208

config?: MuxJWTSignOptionsMultiple

209

): Promise<Tokens>;

210

211

/**

212

* Create a JWT token for DRM license acquisition

213

*/

214

signDrmLicense(

215

playbackId: string,

216

config?: MuxJWTSignOptions

217

): Promise<string>;

218

219

/**

220

* Create a JWT token for signed statistics request

221

*/

222

signViewerCounts(

223

id: string,

224

config?: MuxJWTSignOptions

225

): Promise<string>;

226

}

227

228

interface MuxJWTSignOptions {

229

/** Token type (e.g., 'video', 'thumbnail', 'gif', 'storyboard', 'drm_license') */

230

type?: string;

231

/** Token expiration (e.g., '7d', '1h', '30m') - default: '7d' */

232

expiration?: string;

233

/** Additional JWT claims */

234

params?: object;

235

/** Signing key ID (overrides client.jwtSigningKey) */

236

keyId?: string;

237

/** Private key (overrides client.jwtPrivateKey) */

238

keySecret?: string;

239

}

240

241

interface Tokens {

242

video?: string;

243

thumbnail?: string;

244

gif?: string;

245

storyboard?: string;

246

}

247

```

248

249

[JWT Module Documentation](./jwt.md)

250

251

## Error Handling

252

253

The SDK provides comprehensive error classes for handling API errors.

254

255

```typescript { .api }

256

class MuxError extends Error {}

257

258

class APIError<TStatus, THeaders, TError> extends MuxError {

259

status: TStatus;

260

headers: THeaders;

261

error: TError;

262

}

263

264

class APIUserAbortError extends APIError {}

265

class APIConnectionError extends APIError {}

266

class APIConnectionTimeoutError extends APIConnectionError {}

267

class BadRequestError extends APIError {}

268

class AuthenticationError extends APIError {}

269

class PermissionDeniedError extends APIError {}

270

class NotFoundError extends APIError {}

271

class ConflictError extends APIError {}

272

class UnprocessableEntityError extends APIError {}

273

class RateLimitError extends APIError {}

274

class InternalServerError extends APIError {}

275

```

276

277

## Pagination

278

279

List endpoints return paginated responses with iteration support.

280

281

```typescript { .api }

282

class PageWithTotal<Item> {

283

data: Array<Item>;

284

total_row_count: number;

285

timeframe: Array<number>;

286

limit: number;

287

288

getPaginatedItems(): Array<Item>;

289

nextPageInfo(): PageInfo | null;

290

/** @deprecated Use nextPageInfo() instead */

291

nextPageParams(): Partial<PageWithTotalParams> | null;

292

}

293

294

class BasePage<Item> {

295

data: Array<Item>;

296

297

getPaginatedItems(): Array<Item>;

298

nextPageInfo(): PageInfo | null;

299

/** @deprecated Use nextPageInfo() instead */

300

nextPageParams(): Partial<BasePageParams> | null;

301

}

302

303

interface PageInfo {

304

params?: Record<string, any>;

305

url?: URL;

306

}

307

```

308

309

## Upload Utilities

310

311

Helper functions for creating file uploads.

312

313

```typescript { .api }

314

/**

315

* Create a File object from various data formats

316

*/

317

async function toFile(

318

value: ToFileInput | PromiseLike<ToFileInput>,

319

name?: string | null,

320

options?: FilePropertyBag

321

): Promise<FileLike>;

322

323

/**

324

* Create a File from a file system path (Node.js only)

325

*/

326

function fileFromPath(path: string): Promise<FileLike>;

327

328

type ToFileInput = Uploadable | BlobLikePart | AsyncIterable<BlobLikePart>;

329

type Uploadable = FileLike | ResponseLike | FsReadStream;

330

331

interface FileLike {

332

name: string;

333

lastModified: number;

334

size: number;

335

type: string;

336

text(): Promise<string>;

337

slice(start?: number, end?: number): FileLike;

338

}

339

```

340

341

## Common Types

342

343

```typescript { .api }

344

interface PlaybackID {

345

/** Unique identifier for the PlaybackID */

346

id: string;

347

/** Access control policy */

348

policy: PlaybackPolicy;

349

/** DRM configuration ID (required when policy is 'drm') */

350

drm_configuration_id?: string;

351

}

352

353

type PlaybackPolicy = 'public' | 'signed' | 'drm';

354

```

355