Skip to content

Repository files navigation

FastPix Node.js SDK

npm version npm downloads license Node.js 18+

A robust, type-safe Node.js SDK designed for seamless integration with the FastPix API platform.

The FastPix Node.js SDK is a type-safe Node.js client for the FastPix video API. From any Node.js application you can upload and manage videos, run live streams and simulcasts, create and secure playback IDs, manage playlists and signing keys, pull video analytics (views, metrics, dimensions, and errors), and drive in-video AI features such as subtitles, chapters, summaries, and content moderation.

Supported Node.js: 18 and later Package: @fastpix/fastpix-node Authentication: HTTP Basic Authentication Module systems: ES modules (ESM) and CommonJS

📖 Docs: https://fastpix.com/docs/language-sdks/nodejs-sdk  ·  🚀 Free account: https://dashboard.fastpix.com


Start here

If you are using the FastPix Node.js SDK for the first time, follow these steps in order:

  1. Check your Node.js version.
  2. Create a Node.js project.
  3. Configure the project to use ES modules.
  4. Install the SDK.
  5. Verify that the SDK can be imported.
  6. Configure your FastPix credentials.
  7. Initialize the FastPix client.
  8. Create your first media asset.
  9. Retrieve the media asset using its media ID.
  10. Verify the API response.

Do not skip the verification steps. If installation, the ES module configuration, or authentication fails, troubleshoot that problem before continuing to the next API operation.


Before you begin

To use the SDK, make sure you have:

  • Node.js 18 or later.
  • npm.
  • A FastPix account.
  • A FastPix Access Token.
  • A FastPix Secret Key.

FastPix uses Basic Authentication:

SDK value FastPix credential
username Access Token
password Secret Key

You can obtain your credentials from the FastPix Dashboard. Follow the steps in the Authentication with Basic Auth guide to obtain your credentials.

  1. Check your Node.js version

Run:

node --version

Output is similar to:

v20.19.0

or a later version.

The FastPix Node.js SDK supports Node.js 18 and later.

If your Node.js version is earlier than 18, install a supported version before continuing.

You can also verify your npm version:

npm --version

Output is similar to:

10.8.2
  1. Create a Node.js project

a. Create a new directory for your FastPix application

mkdir fastpix-node-sdk-demo
cd fastpix-node-sdk-demo

b. Initialize the Node.js project

npm init -y

This creates a package.json file.

c. Configure the project to use ES modules

Open package.json and add:

"type": "module"

For example:

{
  "name": "fastpix-node-sdk-demo",
  "version": "1.0.0",
  "type": "module",
  "description": "FastPix Node.js SDK demo",
  "main": "example.js",
  "scripts": {
    "start": "node example.js"
  }
}

The "type": "module" setting tells Node.js to treat .js files in this project as ES modules.

This allows you to use ES module syntax:

import { Fastpix } from "@fastpix/fastpix-node";

instead of CommonJS syntax:

const { Fastpix } = require("@fastpix/fastpix-node");
  1. Install the SDK

a. Install the FastPix Node.js SDK using npm:

npm install @fastpix/fastpix-node

The SDK is added to your project's dependencies and installed in the node_modules directory.

You can verify the installed package with:

npm list @fastpix/fastpix-node

Output is similar to:

fastpix-node-sdk-demo@1.0.0
└── @fastpix/fastpix-node@<version>

b. Verify that the project is using ES modules

Create a file named example.js:

touch example.js

Add:

console.log("ES modules are enabled");

Run:

node example.js

Output is similar to:

ES modules are enabled

If this command fails, verify that "type": "module" is present in package.json before continuing.

  1. Verify the installation

Before making an API request, verify that Node.js can import the SDK.

Replace the contents of example.js with:

import { Fastpix } from "@fastpix/fastpix-node";

console.log("FastPix SDK imported successfully");

Run:

node example.js

Output is similar to:

FastPix SDK imported successfully

If this command fails, do not continue to API calls.

Check:

  • Node.js 18 or later is installed.
  • The project uses "type": "module".
  • @fastpix/fastpix-node is installed.
  • You are running the command from the project directory.
  • Your Node.js interpreter is the expected version.

You can verify the installed package with:

npm list @fastpix/fastpix-node

  1. Configure authentication

FastPix uses Basic Authentication.

Set the Access Token and Secret Key as environment variables.

macOS and Linux

export FASTPIX_USERNAME="<YOUR_ACCESS_TOKEN>"
export FASTPIX_PASSWORD="<YOUR_SECRET_KEY>"

Windows PowerShell

$env:FASTPIX_USERNAME="<YOUR_ACCESS_TOKEN>"
$env:FASTPIX_PASSWORD="<YOUR_SECRET_KEY>"

The SDK maps these variables as follows:

FASTPIX_USERNAME → Access Token
FASTPIX_PASSWORD → Secret Key

Verify the credentials are set

Do not print the actual credential values.

Instead, run:

macOS and Linux

node -e 'console.log("Access Token:", process.env.FASTPIX_USERNAME ? "set" : "missing"); console.log("Secret Key:", process.env.FASTPIX_PASSWORD ? "set" : "missing")'

Windows PowerShell

node -e "console.log('Access Token:', process.env.FASTPIX_USERNAME ? 'set' : 'missing'); console.log('Secret Key:', process.env.FASTPIX_PASSWORD ? 'set' : 'missing')"

Output is similar to:

Access Token: set
Secret Key: set

Security

Never:

  • Commit credentials to Git.
  • Put credentials directly into source code.
  • Include credentials in screenshots, logs, or bug reports.
  • Print authentication headers during debugging in production.

Use environment variables or a secure credential-management system.


  1. Initialize the FastPix client

a. Create a file named example.js

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  security: {
    username: process.env.FASTPIX_USERNAME,
    password: process.env.FASTPIX_PASSWORD,
  },
});

console.log("FastPix client initialized");

b. Run:

node example.js

Output is similar to:

FastPix client initialized

What this code does

Fastpix is the top-level SDK client.

The security object contains the credentials used to authenticate API requests.

The SDK client does not make an API request simply because it is initialized.

An API request occurs when you call an operation such as:

fastpix.inputVideo.create(...)
  1. Make your first API request

The easiest way to verify the complete integration is to create media from a publicly accessible video URL.

FastPix provides a sample video URL:

https://static.fastpix.com/fp-sample-video.mp4

a. Replace the contents of example.js with:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  security: {
    username: process.env.FASTPIX_USERNAME,
    password: process.env.FASTPIX_PASSWORD,
  },
});

async function run() {
  const response = await fastpix.inputVideo.create({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.com/fp-sample-video.mp4",
      },
    ],
    metadata: {
      source: "fastpix-node-sdk-demo",
    },
  });

  console.log(JSON.stringify(response, null, 2));
}

run().catch((error) => {
  console.error("FastPix API request failed");
  console.error(error);
  process.exit(1);
});

b. Save the file and run:

node example.js
  1. Verify the API response

A successful request returns a response containing a media ID.

The response has the following general structure:

{
  "success": true,
  "data": {
    "id": "5157e363-5abb-414d-83c7-520ecdc9f5fd",
    "status": "Created"
  }
}

The value of:

data.id

is the unique ID assigned to the media.

A media_id is different from a playback_id. They identify different resources and are used for different operations.


  1. Retrieve the media asset

Use the media ID returned by the create operation to retrieve the media asset.

Add the following code after the media is created:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  security: {
    username: process.env.FASTPIX_USERNAME,
    password: process.env.FASTPIX_PASSWORD,
  },
});

async function run() {
  console.log("Creating media...");

  const createResult = await fastpix.inputVideo.create({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.com/fp-sample-video.mp4",
      },
    ],
    metadata: {
      source: "fastpix-node-sdk-demo",
    },
  });

  console.log(
    "CREATE MEDIA",
    JSON.stringify(createResult, null, 2),
  );

  const mediaId = createResult.data.id;

  console.log("\nMEDIA ID:");
  console.log(mediaId);

  console.log("\nRetrieving media...");

  const mediaResult = await fastpix.manageVideos.get({
    mediaId,
  });

  console.log(
    "\nGET MEDIA",
    JSON.stringify(mediaResult, null, 2),
  );
}

run().catch((error) => {
  console.error("\nFastPix API request failed");
  console.error(error);
  process.exit(1);
});

Run:

node example.js

The output should contain:

Creating media...

followed by the create response and:

Media ID: <media-id>
Retrieving media...

followed by the media response.

A successful response from the get-media operation confirms that:

  • The SDK authenticated successfully.
  • The media was created successfully.
  • A media ID was returned.
  • The media ID can be used in a subsequent API operation.
  • The Node.js SDK can communicate successfully with the FastPix API.

At this point, the initial SDK integration is complete.

What you have verified

By completing this guide, you have verified that:

  • Node.js is installed and supported.
  • Your project is configured to use ES modules.
  • The FastPix Node.js SDK is installed.
  • Node.js can import the SDK.
  • Your FastPix credentials are configured.
  • The FastPix client can be initialized.
  • Your application can authenticate with the FastPix API.
  • You can create a media asset.
  • You can retrieve the media asset using its media ID.

Your completed workflow is:

Node.js application
        |
        v
FastPix Node.js SDK
        |
        v
FastPix API
        |
        v
Create media
        |
        v
media_id
        |
        v
Get media

You are now ready to use the returned media_id with other FastPix API operations.

Available Resources and Operations

Comprehensive Node.js SDK for FastPix platform integration with full API coverage.

Media API

Upload, manage, and transform video content with comprehensive media management capabilities.

For detailed documentation, see FastPix Video on Demand Overview.

Input Video

Manage Videos

Playback

Playlist

Signing Keys

DRM Configurations

Live API

Stream, manage, and transform live video content with real-time broadcasting capabilities.

For detailed documentation, see FastPix Live Stream Overview.

Start Live Stream

  • Create Stream - Initialize new live streaming session with DVR mode support

Manage Live Stream

Live Playback

Simulcast Stream

Video Data API

Monitor video performance and quality with comprehensive analytics and real-time metrics.

For detailed documentation, see FastPix Video Data Overview.

Metrics

Views

Dimensions

Transformations

Transform and enhance your video content with powerful AI and editing capabilities.

In-Video AI Features

Enhance video content with AI-powered features including moderation, summarization, and intelligent categorization.

Media Clips

Subtitles

Media Tracks

Access Control

Format Support

Standalone functions

All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.

To read more about standalone functions, check FUNCTIONS.md.

Available standalone functions

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  security: {
    username: "your-access-token",
    password: "your-secret-key",
  },
});

async function run() {
  const result = await fastpix.inputVideo.create({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.com/fp-sample-video.mp4",
      },
    ],
    metadata: {
      "key1": "value1",
    },
  }, {
    retries: {
      strategy: "backoff",
      backoff: {
        initialInterval: 1,
        maxInterval: 50,
        exponent: 1.1,
        maxElapsedTime: 100,
      },
      retryConnectionErrors: false,
    },
  });

  console.log(JSON.stringify(result, null, 2));
}

run();

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  security: {
    username: "your-access-token",
    password: "your-secret-key",
  },
});

async function run() {
  const result = await fastpix.inputVideo.create({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.com/fp-sample-video.mp4",
      },
    ],
    metadata: {
      "key1": "value1",
    },
  });

  console.log(JSON.stringify(result, null, 2));
}

run();

Error Handling

FastpixError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
error.message string Error message
error.statusCode number HTTP response status code eg 404
error.headers Headers HTTP response headers
error.body string HTTP body. Can be empty string if no body is returned.
error.rawResponse Response Raw HTTP response

Example

import { Fastpix } from "@fastpix/fastpix-node";
import * as errors from "@fastpix/fastpix-node/models/errors";

const fastpix = new Fastpix({
  security: {
    username: "your-access-token",
    password: "your-secret-key",
  },
});

async function run() {
  try {
    const result = await fastpix.inputVideo.create({
      inputs: [
        {
          type: "video",
          url: "https://static.fastpix.com/fp-sample-video.mp4",
        },
      ],
      metadata: {
        "key1": "value1",
      },
    });

    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    if (error instanceof errors.FastpixError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);
    }
  }
}

run();

Error Classes

Primary error:

Less common errors (6)

Network errors:

Inherit from FastpixError:

  • ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. See error.rawValue for the raw value and error.pretty() for a nicely formatted multi-line string.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  serverURL: "https://api.fastpix.com/v1/",
  security: {
    username: "your-access-token",
    password: "your-secret-key",
  },
});

async function run() {
  const result = await fastpix.inputVideo.create({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.com/fp-sample-video.mp4",
      },
    ],
    metadata: {
      "key1": "value1",
    },
  });

  console.log(JSON.stringify(result, null, 2));
}

run();

Custom HTTP Client

The TypeScript SDK makes API calls using an HTTPClient that wraps the native Fetch API. This client is a thin wrapper around fetch and provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient constructor takes an optional fetcher argument that can be used to integrate a third-party HTTP client or when writing tests to mock out the HTTP client and feed in fixtures.

The following example shows how to use the "beforeRequest" hook to to add a custom header and a timeout to requests and how to use the "requestError" hook to log errors:

import { Fastpix } from "@fastpix/fastpix-node";
import { HTTPClient } from "@fastpix/fastpix-node/lib/http";

const httpClient = new HTTPClient({
  // fetcher takes a function that has the same signature as native `fetch`.
  fetcher: (request) => {
    return fetch(request);
  }
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000)
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new Fastpix({ httpClient: httpClient });

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches console's interface as an SDK option.

Warning

Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

import { Fastpix } from "@fastpix/fastpix-node";

const sdk = new Fastpix({ debugLogger: console });

You can also enable a default debug logger by setting an environment variable FASTPIX_DEBUG to true.

Webhooks

FastPix signs every webhook delivery. The SDK's webhooks resource verifies that signature and returns the parsed, trusted event in one call — so you never act on a forged payload.

The signing secret is separate from your API credentials (it's the base64 secret from the FastPix dashboard). Provide it via the webhookSecret option, or let it default to the FASTPIX_WEBHOOK_SECRET environment variable.

The one call

// Verifies the signature, then returns the parsed event. Throws
// WebhookVerificationError if the signature is missing, wrong, or the body
// isn't the raw bytes. `rawBody` must be the unparsed request body.
const event = fastpix.webhooks.unwrap(rawBody, headers);

event is a typed, discriminated union — switch (event.type) narrows event.data (Media for video.media.*, the live-stream payload for video.live_stream.*).

Express example

import express from "express";
import { Fastpix, WebhookVerificationError } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({ webhookSecret: process.env.FASTPIX_WEBHOOK_SECRET });
const app = express();
const seen = new Set<string>(); // use a durable store (Redis/DB) in production

app.post(
  "/webhooks/fastpix",
  express.raw({ type: "application/json" }), // REQUIRED: verify over the raw bytes
  (req, res) => {
    const signature = req.header("FastPix-Signature");
    const rawText = req.body?.toString("utf8") ?? "";

    // Dashboard validation probe: unsigned, empty/"{}" body → ack with 200 first.
    if (!signature && (rawText.trim() === "" || rawText.trim() === "{}")) {
      return res.status(200).send("ok");
    }

    try {
      const event = fastpix.webhooks.unwrap(req.body, req.headers);

      if (seen.has(event.id)) return res.status(202).send("duplicate"); // dedupe on id
      seen.add(event.id);

      switch (event.type) {
        case "video.media.ready":
        case "video.media.updated":
          console.log(`media ${event.object.id} -> ${event.data.status}`); // data: Media
          break;
        case "video.live_stream.created":
          console.log(`stream ${event.data.streamId} created`); // data: live-stream
          break;
        default:
          console.log(`unhandled: ${event.type}`);
      }
      return res.status(202).send("accepted");
    } catch (err) {
      if (err instanceof WebhookVerificationError) {
        return res.status(400).send("invalid signature"); // bad signature
      }
      throw err; // unexpected → 500
    }
  },
);

app.listen(3000, () => console.log("Listening on :3000/webhooks/fastpix"));

CommonJS: swap the imports for const express = require("express"); and const { Fastpix, WebhookVerificationError } = require("@fastpix/fastpix-node"); — everything else is identical.

Troubleshooting

Symptom Fix
400 "must be the raw request payload" Use express.raw({ type: "application/json" }), not express.json().
Dashboard says endpoint not connecting Return 200 to the unsigned empty/{} validation probe before verifying.
400 "signature mismatch" on your own test Base64-decode the secret first: createHmac("sha256", Buffer.from(secret, "base64")). Sign the exact body bytes you send.
No events arrive at all http://localhost isn't reachable — register a public tunnel URL (e.g. npx ngrok http 3000).

No timestamp is signed, so there is no replay window — enforce idempotency by deduping on the top-level event id.

Full reference (event envelope, typed events, local testing, all gotchas): docs/webhooks.md. Standalone example: examples/webhooksServer.example.ts.


FAQ

How do I install the FastPix Node.js SDK? Run npm install @fastpix/fastpix-node (or the pnpm/yarn/bun equivalent). See Start here.

How do I authenticate the SDK? FastPix uses Basic Auth: pass your access token as the username and your secret key as the password when constructing the client. See Before you begin.

Does it support TypeScript, ESM, and CommonJS? Yes - the package ships TypeScript type definitions and works with both ES modules and CommonJS. See Start here.

How do I upload a video in Node.js? Create media from a URL or a direct upload through the input-video resource on the client. See Start here and Available Resources and Operations.

How do I start a live stream? Use the Live API resources to create and manage streams, simulcasts, and live playback IDs. See Available Resources and Operations.

How do I get video analytics and metrics in Node.js? The Video Data API exposes metrics, views, dimensions, and errors for quality-of-experience monitoring. See Available Resources and Operations.

How do I verify FastPix webhooks in Node.js? The SDK includes webhook signature verification. See Webhooks.

How do I handle API errors? Wrap calls in try/catch; the SDK throws typed errors exposing the message, status code, and response body. See Error Handling.

How do I configure automatic retries? Pass a retry configuration per call or at client initialization to control the backoff strategy. See Retries.

How do I use a custom HTTP client, proxy, or timeout? Provide your own HTTP client to configure timeouts, proxies, and custom headers, or add request/response hooks. See Custom HTTP Client.

How do I import only the functions I need (tree-shaking)? Use the standalone functions instead of the full client for smaller bundles. See Standalone functions.

Which Node.js versions are supported? Node.js 18 and above. See Before you begin.


Which FastPix SDK should I use?

FastPix publishes a server SDK for every major backend language, each generated from the same API specification:

Language Repo Install
Node.js / TypeScript (this repo) node-sdk npm install @fastpix/fastpix-node
PHP fastpix-php composer require fastpix/sdk
Python fastpix-python pip install fastpix-python
Go fastpix-go go get github.com/FastPix/fastpix-go
Java fastpix-java io.fastpix:sdk (Maven/Gradle)
C# / .NET fastpix-sdk-csharp dotnet add package Fastpix
Ruby fastpix-ruby gem install fastpixapi

To upload and play the media these SDKs create, use the FastPix browser libraries: web-uploads-sdk, react-web-uploader, and web-player-component. Browse everything in the FastPix organization.


Development

This Node.js SDK is programmatically generated from our API specifications. Any manual modifications to internal files will be overwritten during subsequent generation cycles.

We value community contributions and feedback. Feel free to submit pull requests or open issues with your suggestions, and we'll do our best to include them in future releases.

Detailed Usage

For comprehensive understanding of each API's functionality, including detailed request and response specifications, parameter descriptions, and additional examples, please refer to the FastPix API Reference.

The API reference offers complete documentation for all available endpoints and features, enabling developers to integrate and leverage FastPix APIs effectively.

About

Official FastPix Node.js SDK - a type-safe TypeScript / JavaScript client for the FastPix video API: media uploads, live streaming, playback IDs, playlists, video analytics, webhooks, and in-video AI. npm: @fastpix/fastpix-node

Topics

Resources

Contributing

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages