• Stars
    star
    152
  • Rank 244,685 (Top 5 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Official Mux API wrapper for Node projects, supporting both Mux Data and Mux Video.

Mux Node Banner

@mux/mux-node

NPM | Package Docs | Mux Docs | Mux API Reference

Official Mux API wrapper for Node projects, supporting both Mux Data and Mux Video.

Mux Video is an API-first platform, powered by data and designed by video experts to make beautiful video possible for every development team.

Mux Data is a platform for monitoring your video streaming performance with just a few lines of code. Get in-depth quality of service analytics on web, mobile, and OTT devices.

This library is intended to provide Mux API convenience methods for applications written in server-side Javascript. Please note that this package uses Mux access tokens and secret keys and is intended to be used in server-side code only.

Not familiar with Mux? Check out https://mux.com/ for more information.

Documentation

See the Mux-Node docs

Installation

npm install @mux/mux-node --save

or

yarn add @mux/mux-node

Usage

Please note: The instructions below are for CommonJS modules and the use thereof (require in vanilla NodeJS). This library also exports an experimental ESModule and all you should need to do is import Mux from '@mux/mux-node' in place of require('@mux/mux-node') below. If you run into any problems, please file an issue!

To start, you will need a Mux access token and secret for your Mux environment. For more information on where to get an access token, visit the Mux Getting Started guide https://docs.mux.com/docs

Require the @mux/mux-node npm module and create a Mux instance. Your Mux instance will have Data and Video properties that will allow you to access the Mux Data and Video APIs.

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

// make it possible to read credentials from .env files
const dotenv = require('dotenv');
dotenv.config();

const { Video, Data } = new Mux(accessToken, secret);

If a token ID and secret aren't included as parameters, the SDK will attempt to use the MUX_TOKEN_ID and MUX_TOKEN_SECRET environment variables.

// assume process.env.MUX_TOKEN_ID and process.env.MUX_TOKEN_SECRET contain your credentials
const muxClient = new Mux(); // Success!

As an example, you can create a Mux asset and playback ID by using the below functions on your Video instance.

// Create an asset
const asset = await Video.Assets.create({
  input: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4',
  "playback_policy": [
    "public" // makes playback ID available on the asset
  ],
});

Or, if you don't have the files online already, you can ingest one via the direct uploads API.

const fs = require('fs')
const fetch = require('node-fetch');
let upload = await Video.Uploads.create({
  new_asset_settings: { playback_policy: 'public' },
});

// The URL you get back from the upload API is resumable, and the file can be uploaded using a `PUT` request (or a series of them).
const readStream = await fs.createReadStream('/path/to/your/file');
await fetch(upload.url, { method: 'PUT', body: readStream });

// The upload may not be updated immediately, but shortly after the upload is finished you'll get a `video.asset.created` event and the upload will now have a status of `asset_created` and a new `asset_id` key.
let updatedUpload = await Video.Uploads.get(upload.id);

// Or you could decide to go get additional information about that new asset you created.
let asset = await Video.Assets.get(updatedUpload['asset_id']);

You can access the Mux Data API in the same way by using your Data instance. For example, you can list all of the values across every breakdown for the aggregate_startup_time metric by using the below function.

const breakdown = await Data.Metrics.breakdown('aggregate_startup_time', {
  group_by: 'browser',
});

Usage Details

Every function will return a chainable Promise.

Video.Assets.create({
  input: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4',
}).then((asset) => {
  /* Do things with the asset */
});

Verifying Webhook Signatures

Verifying Webhook Signatures is optional. Learn more in our Webhook Security Guide

/*
  If the header is valid, this will return `true`
  If invalid, this will throw one of the following errors:
    * new Error('Unable to extract timestamp and signatures from header')
    * new Error('No signatures found with expected scheme');
    * new Error('No signatures found matching the expected signature for payload.')
    * new Error('Timestamp outside the tolerance zone')
*/

/*
  `rawBody` is the raw request body. It should be a string representation of a JSON object.
  `header` is the value in request.headers['mux-signature']
  `secret` is the signing secret for this configured webhook. You can find that in your webhooks dashboard
           (note that this secret is different than your API Secret Key)
*/

Mux.Webhooks.verifyHeader(rawBody, header, secret);

Note that when passing in the payload (rawBody) you want to pass in the raw un-parsed request body, not the parsed JSON. Here's an example if you are using express.

const Mux = require('@mux/mux-node');
const { Webhooks } = Mux;
const express = require('express');
const bodyParser = require('body-parser');

/**
 * You'll need to make sure this is externally accessible.  ngrok (https://ngrok.com/)
 * makes this really easy.
 */

const webhookSecret = process.env.WEBHOOK_SECRET;
const app = express();

app.post(
  '/webhooks',
  bodyParser.raw({ type: 'application/json' }),
  async (req, res) => {
    try {
      const sig = req.headers['mux-signature'];
      // will raise an exception if the signature is invalid
      const isValidSignature = Webhooks.verifyHeader(
        req.body,
        sig,
        webhookSecret
      );
      console.log('Success:', isValidSignature);
      // convert the raw req.body to JSON, which is originally Buffer (raw)
      const jsonFormattedBody = JSON.parse(req.body);
      // await doSomething();
      res.json({ received: true });
    } catch (err) {
      // On error, return the error message
      return res.status(400).send(`Webhook Error: ${err.message}`);
    }
  }
);

app.listen(3000, () => {
  console.log('Example app listening on port 3000!');
});

JWT Helpers (API Reference)

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}

// And, 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}

// Also, let's sign a Real-Time Space ID
const spaceToken = Mux.JWT.signSpaceId('some-space-id')

request and response events

The SDK returns the data key for every object, because in the Mux API that's always the thing you actually want to see. Sometimes, however, it's useful to see more details about the request being made or the full response object. You can listen for request and response events to get these raw objects.

muxClient.on('request', (req) => {
  // Request will contain everything being sent such as `headers, method, base url, etc
});

muxClient.on('response', (res) => {
  // Response will include everything returned from the API, such as status codes/text, headers, etc
});

See the Mux-Node docs for a list of all available functions.

Development

Run unit tests: yarn test or yarn test:unit

Run integration tests: yarn test:int - this will run integration tests with nock and NOCK_BACK_MODE set to record. This means that previously recorded API requests will be stubbed and any missing ones will be recorded.

You can also run integration tests with real requests by running yarn test:int:wild. Make sure you have MUX_TOKEN_ID and MUX_TOKEN_SECRET set as environment variables so your requests are authenticated. This is useful to run locally to verify that actual API requests work as expected. When running the whole suite locally you might run into Mux API rate limits so keep that in mind.

Pro Tip Use mocha -g option to run only a specific test or group of tests. For example: yarn test -g 'creates a new Assets'.

To generate the ESDocs, run:

yarn esdoc
open ./docs/index.html

Contributing

Find a bug or want to add a useful feature? That'd be amazing! If you'd like to submit a pull request to the project with changes, please do something along these lines:

  1. Fork the project wherever you'd like
  2. Create a meaningful branch name that relates to your contribution. Consider including an issue number if available. git co -b add-node-lts-support
  3. Make any changes you'd like in your forked branch.
  4. Add any relevant tests for your changes
  5. Open the pull request! 🎉

Running integration tests will require a Mux account with valid seed data for /video and /data endpoints. If you are contributing and you don't have this, please add unit test coverage and someone from the Mux will help get integration tests added if necessary.

More Repositories

1

media-chrome

Custom elements (web components) for making audio and video player controls that look great in your website or app.
TypeScript
1,215
star
2

next-video

The easiest way to add video in your Nextjs app.
TypeScript
757
star
3

stream.new

The repo for https://stream.new
TypeScript
499
star
4

upchunk

Uploads Chunks! Takes big files, splits them up, then uploads each one with care (and PUT requests).
TypeScript
335
star
5

meet

A meeting app built on Mux Real-Time Video.
TypeScript
278
star
6

elements

Custom elements for working with media in the browser that Just Work™
TypeScript
235
star
7

certificate-expiry-monitor

Utility that exposes the expiry of TLS certificates as Prometheus metrics
Go
160
star
8

video-course-starter-kit

A starter template to help create a video course with Mux + Next.js
TypeScript
131
star
9

player.style

A fresh collection of media player themes for every use case!
HTML
125
star
10

examples

Example playground!
TypeScript
110
star
11

mux-go

Official Mux API wrapper for golang projects, supporting both Mux Data and Mux Video.
Go
89
star
12

webrtc-rebroadcaster

A "simple" webrtc rebroadcaster using FFmpeg
C++
88
star
13

mux-elixir

Official Mux API wrapper for Elixir projects, supporting both Mux Data and Mux Video.
Elixir
77
star
14

chromium_broadcast_demo

A simple demo showing how to use chromium as a WebRTC rendering engine
HTML
67
star
15

hlstools

Tools for analyzing and processing hls streams
C++
65
star
16

mux-ruby

Official Mux API wrapper for ruby projects, supporting both Mux Data and Mux Video.
Ruby
50
star
17

mux-python

Official Mux API wrapper for python projects, supporting both Mux Data and Mux Video.
Python
47
star
18

mux-stats-sdk-avplayer

Mux integration with `AVPlayer` for iOS Native Applications
Objective-C
43
star
19

mux-php

Official Mux API wrapper for PHP projects, supporting both Mux Data and Mux Video.
PHP
38
star
20

hls-video-element

A custom element (web component) for playing HTTP Live Streaming (HLS) videos.
JavaScript
38
star
21

youtube-video-element

A custom element (web component) for the YouTube player.
JavaScript
33
star
22

videojs-mux-kit

JavaScript
33
star
23

vmaf_analyzer

Estimates the average delivered VMAF for hls manifests
Go
32
star
24

example-ios-live-streaming

An example app for live streaming from an iOS device using the Mux live streaming service.
Swift
30
star
25

castable-video

Cast your video element to the big screen with ease!
JavaScript
25
star
26

strapi-plugin-mux-video-uploader

A Strapi plugin for managing uploads to Mux.
TypeScript
23
star
27

example-android-live-streaming

C++
23
star
28

videojs-super-resolution

Super Resolution for Video JS
JavaScript
21
star
29

truckload

Migrate your videos to any supported service
TypeScript
19
star
30

mux-stats-sdk-exoplayer

Monitors an ExoPlayer instance and reports player analytics to Mux Data
Java
19
star
31

mux-stats-sdk-react-native-video

JavaScript
17
star
32

stats-sdk-objc

Mux Stats SDK for iOS and tvOS
Objective-C
16
star
33

media-playlist

A custom element for playing through a set of audio and video elements.
JavaScript
15
star
34

bot-watcher

Example of using headless Chrome to test different aspects of a player
JavaScript
15
star
35

blurhash

Using woltapp/blurhash to make nice placeholders for Mux videos. Works nicely with Mux Player.
TypeScript
14
star
36

media-elements

A collection of HTMLMediaElement compatible elements and add-ons
JavaScript
13
star
37

cli

Command Mux from the command line like a boss.
TypeScript
11
star
38

media-group

👯‍♀️ mediagroup / MediaController which can be used to sync and control multiple audio / video elements
TypeScript
11
star
39

media-offset

✂️ Configures a media element to lock playback to a defined segment of the media
JavaScript
11
star
40

trivia.dev

IT'S TRIVIA! FOR DEVS! GO!
JavaScript
10
star
41

chromium_livestreamer

Take web pages and turn them into a live streams
Shell
8
star
42

custom-media-element

A custom element for extending the native media elements (<audio> or <video>)
JavaScript
8
star
43

chunked-transfer-demo

Webserver that demonstrates delivery of HLS media with HTTP chunked transfer encoding
Go
7
star
44

custom-video-element

A custom element for extending the native video element.
JavaScript
7
star
45

mux-csharp

C#
7
star
46

hls-subtitles-vexillographer

A simple proxy service which changes subtitles flags in HLS manifests.
Ruby
6
star
47

swift-upload-sdk

Mux's Video Upload SDK for iOS. The Swift equivalent of UpChunk.
Swift
6
star
48

shaka-video-element

A custom element (web component) for Shaka Player.
JavaScript
6
star
49

mux-player-swift

Use Mux Player Swift to stream and monitor video from Mux with AVKit and AVFoundation
Swift
6
star
50

android-upload-sdk

Mux's Video Upload SDK for Android. The Android equivalent of UpChunk.
Kotlin
5
star
51

chromecast-mux

JavaScript
5
star
52

roku-mux

Brightscript
5
star
53

mux-stats-sdk-media3

Mux Data SDK for AndroidX Media3
Kotlin
5
star
54

web-player-framework

JavaScript
5
star
55

mux-studio-demo

TypeScript
4
star
56

jamstack-conf-2020-workshop

JavaScript
4
star
57

next-video-site

TypeScript
4
star
58

mux-stats-google-ima

Swift
4
star
59

mux-protobuf

Mux Protobuf definition files
3
star
60

mux-android-distribution

A Gradle Plugin for distributing android builds, with support for Artifactory
Groovy
3
star
61

mux-player-android

Java
3
star
62

packaging_examples

Samples files packaged by mux
3
star
63

spaces-livekit-broadcast-layouts

TypeScript
3
star
64

mux-stats-sdk-theoplayer-ios

Mux Data Integration for THEOplayer's iOS SDK
Swift
2
star
65

meetup_colorspace_demo

HTML
2
star
66

mux-stats-sdk-theoplayer-android

Java
2
star
67

protogen

Protobuf Specification Generator written in Go
Go
2
star
68

media-tracks

Polyfill audio and video tracks with renditions.
TypeScript
2
star
69

video-archivist

A helpful Github bot that listens for links to videos in new issues, then asks maintainers if they want to archive it so it doesn't ever go away.
TypeScript
2
star
70

mux-java

Java
2
star
71

blurup

Generate a blurry image placeholder for a Mux video.
HTML
2
star
72

nextjs-backend-example

JavaScript
2
star
73

kaper

Kapacitor client written in Elixir.
Elixir
1
star
74

mux-stats-sdk-mediaplayer

Java
1
star
75

stackpath-urlauth

Golang library to sign Stackpath CDN URLs
Go
1
star
76

stats-sdk-exoplayer

Mux Stats SDK for ExoPlayer
Java
1
star
77

media-woofer

Kick up the bass on your media element!
JavaScript
1
star
78

webos-mux

LG WebOS
JavaScript
1
star
79

mux-docs

Docs for Mux SDKs and APIs
1
star
80

mux-delete-all-assets

Python
1
star
81

mipp

mipp - Pixel processing in JavaScript
C++
1
star
82

.github

Mux's shared templates and workflows.
1
star
83

stats-sdk-android

Core library for our Data SDKs for Android
Kotlin
1
star
84

tizen-mux

JavaScript
1
star
85

mux-stats-sdk-kaltura-android

A library for integration Mux Data with the Kaltura Playkit on Android
Java
1
star
86

blur-up-thumbs

HTML
1
star
87

simple-local-video-test-server

Uses a simple static server to host media files (with expected mimetype mappings).
HTML
1
star
88

templates

Repository of useful templates for use with Mux products
1
star
89

mux-stats-sdk-jwplayer-ios

Mux Data Integration for JWPlayer's iOS SDK
Objective-C
1
star