@newrelic/video-videojs
v4.2.1
Published
New relic tracker for Videojs
Readme
New Relic Video.js Tracker
The New Relic Video.js Tracker provides comprehensive video analytics for applications using Video.js Player. Track video events, monitor playback quality, identify errors, and gain deep insights into user engagement and streaming performance.
Features
- 🎯 Automatic Event Detection - Captures Video.js player events automatically without manual instrumentation
- 📊 Comprehensive Bitrate Tracking - Four distinct bitrate metrics for complete quality analysis
- 🎬 Ad Tracking Support - Full support for IMA, Freewheel, and SSAI (Server-Side Ad Insertion)
- 🔧 Multi-Tech Support - Works with VHS, hls.js, and Shaka Player
- 📈 QoE Metrics - Quality of Experience aggregation for startup time, buffering, and playback quality
- 🎨 Event Segregation - Organized event types:
VideoAction,VideoAdAction,VideoErrorAction,VideoCustomAction - 🌐 Rendition Change Tracking - Monitor quality/rendition changes with automatic rendition change event reporting
- 🚀 Easy Integration - NPM package or direct script include
Table of Contents
- Installation
- Prerequisites
- Usage
- Best Practices
- Configuration Options
- API Reference
- Bitrate Metrics
- Ad Tracking Support
- Quality/Rendition Tracking
- SSAI Guide
- Data Model
- Support
- Contribute
- License
Installation
Option 1: Install via NPM/Yarn
Install the package using your preferred package manager:
NPM:
npm install @newrelic/video-videojsYarn:
yarn add @newrelic/video-videojsOption 2: Direct Script Include (Without NPM)
For quick integration without a build system, include the tracker directly in your HTML:
<!DOCTYPE html>
<html>
<head>
<!-- Video.js Player -->
<link href="https://vjs.zencdn.net/7.20.3/video-js.css" rel="stylesheet" />
<script src="https://vjs.zencdn.net/7.20.3/video.js"></script>
<!-- New Relic Video.js Tracker -->
<script src="path/to/newrelic-video-videojs.min.js"></script>
</head>
<body>
<video id="myVideo" class="video-js" controls width="640" height="480">
<source src="https://your-video-source.mp4" type="video/mp4" />
</video>
<script>
// Initialize Video.js player
var player = videojs('myVideo');
// Configure New Relic tracker with info from one.newrelic.com
const options = {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
};
// Initialize tracker
const tracker = new VideojsTracker(player, options);
</script>
</body>
</html>Setup Steps:
- Get Configuration - Visit one.newrelic.com and follow the Streaming Video & Ads onboarding flow to get your
licenseKey,beacon,applicationID, and integration code snippet. - Integrate - Include the script in your HTML and initialize with your configuration
Prerequisites
Before using the tracker, ensure you have:
- New Relic Account - Active New Relic account with valid application credentials (
beacon,applicationId,licenseKey) - Video.js Player - Video.js player integrated in your application
Optional:
- Quality Tracking Plugin - To track rendition/quality changes, optionally install
videojs-contrib-quality-levels(see Quality/Rendition Tracking section for details). This is not required — the tracker works perfectly without it.
Usage
Getting Your Configuration
Before initializing the tracker, obtain your New Relic configuration:
- Log in to one.newrelic.com
- Navigate to the video agent onboarding flow
- Copy your credentials:
licenseKey,beacon, andapplicationId
Basic Setup
import VideojsTracker from '@newrelic/video-videojs';
// Initialize Video.js player
const player = videojs('myVideo');
// Set player version (required)
player.version = videojs.VERSION;
// Configure tracker with credentials from one.newrelic.com
const options = {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
};
// Initialize tracker
const tracker = new VideojsTracker(player, options);Advanced Configuration
const options = {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
config: {
qoeAggregate: true, // Enable QoE event aggregation
qoeIntervalFactor: 2, // Send QoE events every 2 harvest cycles
},
customData: {
contentTitle: 'My Video Title',
customPlayerName: 'MyCustomPlayer',
customAttribute: 'customValue',
},
};
const tracker = new VideojsTracker(player, options);Best Practices
1. Setting contentTitle
The contentTitle attribute will display a value if your video metadata contains title information. If the metadata does not include a title, contentTitle will not be populated. For best results, ensure you explicitly set this attribute during initialization:
const tracker = new VideojsTracker(player, {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
customData: {
contentTitle: 'My Video Title', // Explicitly set from your metadata
},
});If your title changes dynamically (e.g., playlist or queue):
tracker.setOptions({
customData: {
contentTitle: 'New Video Title',
},
});2. Setting userId
Set a user identifier to track video analytics per user:
// Set userId during initialization
const tracker = new VideojsTracker(player, {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
customData: {
contentTitle: 'Video Title',
userId: 'user-12345',
},
});
// Or set userId separately using the API method
tracker.setUserId('user-12345');3. Adding Custom Attributes for Your Deployment
Add custom attributes unique to your deployment to improve data aggregation and analysis:
const tracker = new VideojsTracker(player, {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
customData: {
// Required for identification
contentTitle: videoMetadata.title,
userId: currentUser.id,
// Custom attributes for your deployment
subscriptionTier: 'premium', // User subscription level
contentProvider: 'studio-abc', // Content source
region: 'us-west-2', // Geographic region
cdnProvider: 'cloudflare', // CDN being used
deviceType: 'desktop', // Device category
appVersion: '2.1.0', // Your app version
campaign: 'spring-promo', // Marketing campaign
},
});Use these attributes in New Relic queries:
-- Analyze by subscription tier
SELECT count(*) FROM VideoAction WHERE actionName = 'CONTENT_START'
FACET subscriptionTier SINCE 1 day ago
-- Monitor by region
SELECT average(contentNetworkDownloadBitrate) FROM VideoAction
FACET region SINCE 1 hour ago4. Gradual Rollout with Feature Flags
When deploying to production, use feature flags to enable the tracker gradually. This helps you:
- Validate data collection without impacting all users
- Monitor performance impact at scale
- Catch issues before full deployment
- Control monitoring costs
// Example using a feature flag
const rolloutPercentage = 5; // Start with 5% of users
function shouldEnableTracking(userId) {
// Simple percentage-based rollout
const hash = userId
.split('')
.reduce((acc, char) => acc + char.charCodeAt(0), 0);
return hash % 100 < rolloutPercentage;
}
const player = videojs('myVideo');
player.version = videojs.VERSION;
// Only initialize tracker if user is in rollout
if (shouldEnableTracking(currentUser.id)) {
const tracker = new VideojsTracker(player, {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
customData: {
contentTitle: videoMetadata.title,
userId: currentUser.id,
rolloutGroup: `${rolloutPercentage}%`, // Track which rollout group
},
});
}Recommended Rollout Schedule:
| Phase | Percentage | Duration | Validation | | --------- | ---------- | --------- | ---------------------------------- | | Initial | 5% | 2-3 days | Verify data flowing to New Relic | | Early | 15% | 3-5 days | Check data quality and performance | | Expansion | 25% | 5-7 days | Validate across device types | | Majority | 50% | 1-2 weeks | Monitor at scale | | Full | 100% | Ongoing | Complete deployment |
Configuration Options
Ad Tracking
config.ad.type declares which ad category the tracker should wire up. If not set, no ad tracking runs — this is the safe default. Omitting it while passing other options triggers a console warning.
CSAI — Client-Side Ad Insertion
All CSAI frameworks (IMA, Brightcove IMA, Freewheel) share the adsready event path. The tracker auto-detects which one is present — no sub-type needed. Just declare CSAI.
| Value | Constant | Behaviour |
| -------- | ---------------- | -------------------------------------------------------------------------- |
| 'csai' | AD_TRACKING.CSAI | Auto-detects: Brightcove IMA → IMA → Freewheel → generic fallback |
SSAI — Server-Side Ad Insertion
Each SSAI platform has its own SDK and a completely different activation path — they cannot be auto-detected. A sub-type is always required.
| Value | Constant | Behaviour |
| ------------ | ---------------------- | ----------------------------------------------------------------------- |
| 'ssai:dai' | AD_TRACKING.SSAI.DAI | Google DAI (google.ima.dai.api) |
| 'ssai:mt' | AD_TRACKING.SSAI.MT | AWS MediaTailor |
import { AD_TRACKING } from '@newrelic/video-videojs';
// CSAI — one value covers all client-side frameworks
new VideojsTracker(player, { config: { ad: { type: AD_TRACKING.CSAI } } });
// SSAI — sub-type always required
new VideojsTracker(player, { config: { ad: { type: AD_TRACKING.SSAI.DAI } } });
new VideojsTracker(player, { config: { ad: { type: AD_TRACKING.SSAI.MT } } });
// SSAI.MT with custom CDN config
new VideojsTracker(player, {
config: {
ad: {
type: AD_TRACKING.SSAI.MT,
segmentPrefix: '/my-cdn-path/',
},
},
});
// Change at runtime before first loadstart / adsready
tracker.setAdTracking(AD_TRACKING.CSAI);Extending later: add a new key to
AD_TRACKING.SSAI— validation derives from the object automatically. No other changes needed.
QoE (Quality of Experience) Settings
| Option | Type | Default | Description |
| ------------------- | ------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| qoeAggregate | boolean | false | Enable Quality of Experience event aggregation. Set to true to collect QoE metrics like startup time, buffering, and average bitrate. |
| qoeIntervalFactor | number | 1 | Controls QoE event frequency. A value of N sends QoE events once every N harvest cycles. Must be a positive integer. QoE events are always included on first and final harvest cycles. |
Custom Data
Add custom attributes to all events:
customData: {
contentTitle: 'My Video Title', // Override video title
customPlayerName: 'MyPlayer', // Custom player identifier
customPlayerVersion: '1.0.0', // Custom player version
userId: '12345', // User identifier
// Add any custom attributes you need
}Limit: The maximum total number of custom attributes per event is 150. Any attributes beyond this limit will be dropped.
Note: There are special reserved keywords used for default attributes (such as
actionName,contentBitrate,playerName,viewSession, etc.). Please do not use these as custom attribute names, as they will be dropped. See DATAMODEL.md for the complete list of reserved attribute names.
API Reference
Core Methods
tracker.setUserId(userId)
Set a unique identifier for the current user.
tracker.setUserId('user-12345');tracker.setHarvestInterval(milliseconds)
Configure how frequently data is sent to New Relic. Accepts values between 1000ms (1 second) and 300000ms (5 minutes).
tracker.setHarvestInterval(30000); // Send data every 30 secondstracker.sendCustom(actionName, attributes)
Send custom events with arbitrary attributes.
tracker.sendCustom('VideoBookmarked', {
timestamp: Date.now(),
position: player.currentTime(),
userId: 'user-12345',
bookmarkId: 'bookmark-789',
});tracker.setOptions(options)
Update tracker configuration after initialization.
tracker.setOptions({
customData: {
contentTitle: 'New Video Title',
season: '1',
episode: '3',
},
});tracker.setAdTracking(type)
Change the ad tracking mode after the tracker is created. Must be called before the first loadstart or adsready event to take effect.
import { AD_TRACKING } from '@newrelic/video-videojs';
// Valid values: 'csai' | 'ssai:dai' | 'ssai:mt'
tracker.setAdTracking(AD_TRACKING.CSAI);
tracker.setAdTracking(AD_TRACKING.SSAI.MT);Example: Complete Integration
import VideojsTracker from '@newrelic/video-videojs';
// Initialize player and tracker
const player = videojs('myVideo');
player.version = videojs.VERSION;
const tracker = new VideojsTracker(player, {
info: {
licenseKey: 'YOUR_LICENSE_KEY',
beacon: 'YOUR_BEACON_URL',
applicationId: 'YOUR_APP_ID',
},
config: {
qoeAggregate: true,
},
});
// Set user context
tracker.setUserId('user-12345');
// Configure reporting interval
tracker.setHarvestInterval(30000);
// Send custom events
player.on('userEngagement', () => {
tracker.sendCustom('UserEngaged', {
action: 'like',
timestamp: Date.now(),
});
});Bitrate Metrics
The tracker captures four distinct bitrate metrics providing complete quality analysis:
| Attribute | Description | Use Case |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| contentBitrate | Encoding bitrate (in bps) of the currently playing rendition from the manifest | Monitor actual video quality being delivered |
| contentManifestBitrate | Maximum available bitrate (in bps) across all renditions in the manifest. Represents the highest quality capability of the stream | Understand maximum quality potential |
| contentSegmentDownloadBitrate | ABR estimated bandwidth (in bps) from the player's stats object, used by the ABR algorithm for quality switching decisions | Analyze ABR decision-making |
| contentNetworkDownloadBitrate | Instantaneous download throughput (in bps) from the most recent segment download. Represents raw network download speed | Monitor real-time network performance |
Bitrate Monitoring Example
// All bitrate metrics are automatically captured and sent with each event
// Access them in New Relic Insights queries:
// NRQL Query Examples:
// SELECT average(contentNetworkDownloadBitrate) FROM VideoAction WHERE actionName = 'CONTENT_HEARTBEAT'
// SELECT contentBitrate, contentSegmentDownloadBitrate FROM VideoAction WHERE actionName = 'CONTENT_RENDITION_CHANGE'Ad Tracking Support
Supported Ad Technologies
| Category | Frameworks detected | Constant |
|---|---|---|
| CSAI | Google IMA, Brightcove IMA, Freewheel, generic | AD_TRACKING.CSAI |
| SSAI | Google DAI | AD_TRACKING.SSAI.DAI |
| SSAI | AWS MediaTailor | AD_TRACKING.SSAI.MT |
See Configuration Options → Ad Tracking for full usage and examples.
Google DAI Integration
import { AD_TRACKING } from '@newrelic/video-videojs';
const tracker = new VideojsTracker(player, { config: { ad: { type: AD_TRACKING.SSAI.DAI } } });See samples/dai/index.html for a complete example.
AWS MediaTailor Integration
Supports HLS/DASH, VOD/LIVE, multiple ads per break, quartile tracking, and tracking metadata enrichment.
import { AD_TRACKING } from '@newrelic/video-videojs';
player.src({
src: 'https://your-mediatailor-endpoint.mediatailor.region.amazonaws.com/v1/master/...',
type: 'application/x-mpegURL'
});
const tracker = new VideojsTracker(player, { config: { ad: { type: AD_TRACKING.SSAI.MT } } });
// With custom CDN config
const tracker = new VideojsTracker(player, {
config: {
ad: {
type: AD_TRACKING.SSAI.MT,
segmentPrefix: '/my-cdn-path/',
},
},
});Works with default AWS hostnames and custom CDN domains. See docs/ssai.md for custom CDN setup and advanced options.
Quality/Rendition Tracking
The tracker can automatically detect and report rendition (quality) changes when adaptive bitrate (ABR) video is played. This is an optional feature — the tracker works perfectly fine without it.
Optional: Enable Quality Tracking
To enable quality/rendition change tracking, install and include the videojs-contrib-quality-levels plugin:
Step 1: Install the plugin
npm install videojs-contrib-quality-levelsStep 2: Include in your HTML (before the tracker script):
<!-- Video.js Player -->
<link href="https://vjs.zencdn.net/7.20.3/video-js.css" rel="stylesheet" />
<script src="https://vjs.zencdn.net/7.20.3/video.js"></script>
<!-- Quality Levels Plugin (Optional - only needed for rendition tracking) -->
<script src="https://cdn.jsdelivr.net/npm/videojs-contrib-quality-levels/dist/videojs-contrib-quality-levels.min.js"></script>
<!-- New Relic Video.js Tracker -->
<script src="path/to/newrelic-video-videojs.min.js"></script>How It Works
When the plugin is enabled:
- The tracker monitors the quality levels plugin for rendition change events
- When a rendition change occurs (automatic ABR or user-initiated), a
RENDITION_CHANGEevent is sent to New Relic - The event includes quality metadata: bitrate, width, height, and label
- Quality changes are tracked for both content and ad playback
If the plugin is not loaded:
- The tracker continues to work normally
- All video events are tracked (play, pause, buffering, seeking, etc.)
- Quality/rendition change events are simply not captured
- A debug message logs to the console:
[QualityLevels] player.qualityLevels is not a function
Console Debugging
During development, if the plugin is enabled, the tracker logs quality change events to the console:
[QualityLevels] Plugin initialized successfully
[QualityLevels] Change event fired!
[QualityLevels] selectedIndex: 1
[QualityLevels] Selected level: {width: 1280, height: 720, bitrate: 2500000, …}
[QualityLevels] Sending rendition changed eventIf you see this message instead:
[QualityLevels] player.qualityLevels is not a functionIt means the plugin is not loaded or not available. This is fine — the tracker will continue tracking all other video metrics.
NRQL Query Examples
When quality tracking is enabled:
-- Track rendition changes over time
SELECT count(*) FROM VideoAction
WHERE actionName = 'CONTENT_RENDITION_CHANGE'
FACET contentBitrate SINCE 1 day ago
-- Monitor average bitrate during playback
SELECT average(contentBitrate) FROM VideoAction
WHERE actionName = 'CONTENT_HEARTBEAT'
FACET contentRenditionWidth, contentRenditionHeight
SINCE 1 hour ago
-- Analyze quality upgrades vs downgrades
SELECT contentBitrate FROM VideoAction
WHERE actionName = 'CONTENT_RENDITION_CHANGE'
SINCE 24 hours agoSSAI Guide
For customer-facing SSAI integration details, supported MediaTailor behavior, troubleshooting guidance, and sample usage, see docs/ssai.md.
Testing
This project includes comprehensive unit tests for all tracker functionality.
# Install dependencies
npm install
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchFor more details, see test/README.md.
Data Model
The tracker captures comprehensive video analytics across four event types:
- VideoAction - Playback events (play, pause, buffer, seek, quality changes, heartbeats)
- VideoAdAction - Ad events (ad start, quartiles, completions, clicks)
- VideoErrorAction - Error events (playback failures, network errors, media errors)
- VideoCustomAction - Custom events defined by your application
Full Documentation: See DATAMODEL.md for complete event and attribute reference.
Support
Should you need assistance with New Relic products, you are in good hands with several support channels.
If the issue has been confirmed as a bug or is a feature request, please file a GitHub issue.
Support Channels
- New Relic Documentation: Comprehensive guidance for using our platform
- New Relic Community: The best place to engage in troubleshooting questions
- New Relic University: A range of online training for New Relic users of every level
- New Relic Technical Support: 24/7/365 ticketed support. Read more about our Technical Support Offerings
Additional Resources
- DATAMODEL.md - Complete event and attribute reference
- DEVELOPING.md - Building and testing instructions
- REVIEW.md - Code review guidelines
Contribute
We encourage your contributions to improve the Video.js Tracker! Keep in mind that when you submit your pull request, you'll need to sign the CLA via the click-through using CLA-Assistant. You only have to sign the CLA one time per project.
If you have any questions, or to execute our corporate CLA (which is required if your contribution is on behalf of a company), drop us an email at [email protected].
For more details on how best to contribute, see CONTRIBUTING.md.
A note about vulnerabilities
As noted in our security policy, New Relic is committed to the privacy and security of our customers and their data. We believe that providing coordinated disclosure by security researchers and engaging with the security community are important means to achieve our security goals.
If you believe you have found a security vulnerability in this project or any of New Relic's products or websites, we welcome and greatly appreciate you reporting it to New Relic through our bug bounty program.
If you would like to contribute to this project, review these guidelines.
To all contributors, we thank you! Without your contribution, this project would not be what it is today.
License
The Video.js Tracker is licensed under the Apache 2.0 License.
The Video.js Tracker also uses source code from third-party libraries. Full details on which libraries are used and the terms under which they are licensed can be found in the third-party notices document.

