Skip to content

JavaScript SDK for Sirv REST API

By , Head of Sirv StudioUpdated

Open this page in a new chat

Short answer

Sirv's official JavaScript SDK wraps the Sirv REST API, so you can upload, download, search and manage files, metadata, spins and account statistics from your code. Install it with npm install @sirv/rest-api-js, then connect with the client ID and secret from your Sirv account's API settings. The SDK gets and refreshes the access token for you.

After reading this you will know

  • How to install the SDK and connect to your Sirv account
  • Which file, account, statistics and spin methods it offers
  • How to handle errors and limits

The official JavaScript SDK provides a modern, TypeScript-first interface for interacting with the Sirv REST API.

It handles authentication automatically with token refresh and provides async iterators for paginated results.

Resources:

Install the SDK via npm or yarn:

npm install @sirv/rest-api-js
yarn add @sirv/rest-api-js

For browser environments, include via CDN:

<script src="https://unpkg.com/@sirv/rest-api-js/dist/sirv.min.js"></script>
  • Node.js 16 or higher (for Node.js environments)
  • Modern browser with ES6 support (for browser environments)
import { SirvClient } from '@sirv/rest-api-js';
// Initialize the client
const sirv = new SirvClient({
clientId: 'your-client-id',
clientSecret: 'your-client-secret'
});
// Get account information
const account = await sirv.getAccountInfo();
console.log('Account:', account.alias);
// List files in a directory
const files = await sirv.readFolderContents('/');
for (const file of files.contents) {
console.log(file.filename);
}

The SDK handles authentication automatically. When you make your first API call, it obtains an access token using your client credentials.

The token is automatically refreshed before it expires.

const sirv = new SirvClient({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
autoRefreshToken: true // Default: automatically refresh before expiry
});
// Optional: Manually authenticate to verify credentials
try {
await sirv.connect();
console.log('Authenticated successfully');
} catch (error) {
console.error('Authentication failed:', error.message);
}
// Check if connected
if (sirv.isConnected()) {
console.log('Token is valid');
}
// Get current access token
const token = sirv.getAccessToken();
OptionTypeDefaultDescription
clientIdstringrequiredYour API client ID
clientSecretstringrequiredYour API client secret
baseUrlstringhttps://api.sirv.comAPI endpoint
autoRefreshTokenbooleantrueAuto-refresh token before expiry
timeoutnumber30000Request timeout in milliseconds
maxRetriesnumber3Retry failed requests with exponential backoff

Complete file management including upload, download, copy, rename, delete, and metadata operations.

CategoryMethods
File OperationsreadFolderContents(), getFileInfo(), uploadFile(), downloadFile(), copyFile(), renameFile(), deleteFile(), batchDelete(), createFolder(), fetchUrl()
MetadatagetFileMeta(), setFileMeta(), getApprovalFlag(), setApprovalFlag(), getFileTitle(), setFileTitle(), getFileDescription(), setFileDescription(), getProductMeta(), setProductMeta(), getFileTags(), addFileTags(), removeFileTags()
Batch OperationsbatchZip(), batchDelete()
Media & Exportspin2Video(), video2Spin(), exportSpinToAmazon(), exportSpinToWalmart(), exportSpinToHomeDepot(), exportSpinToLowes(), exportSpinToGrainger()
// List folder contents
const files = await sirv.readFolderContents('/images');
// Upload a file (supports paths, buffers, streams)
await sirv.uploadFile('/images/photo.jpg', fileBuffer);
// Upload with options
await sirv.uploadFile('/images/photo.jpg', fileBuffer, {
contentType: 'image/jpeg'
});
// Download a file
const data = await sirv.downloadFile('/images/photo.jpg');
// Copy a file
await sirv.copyFile({
from: '/images/photo.jpg',
to: '/backup/photo.jpg'
});
// Rename/move a file
await sirv.renameFile({
from: '/images/old-name.jpg',
to: '/images/new-name.jpg'
});
// Delete a file
await sirv.deleteFile('/images/photo.jpg');
// Delete multiple files
await sirv.batchDelete(['/images/photo1.jpg', '/images/photo2.jpg']);
// Create a folder
await sirv.createFolder('/images/new-folder');
// Search files
const results = await sirv.searchFiles({
query: 'filename:*.jpg',
from: '/images',
size: 100
});
// Auto-paginating search iterator
for await (const file of sirv.iterateSearchResults({
query: 'extension:.jpg',
from: '/images'
})) {
console.log(file.filename);
}
// Auto-paginating folder contents iterator
for await (const item of sirv.iterateFolderContents('/images')) {
console.log(item.filename);
}
// Get and set file metadata
const meta = await sirv.getFileMeta('/images/photo.jpg');
await sirv.setFileMeta('/images/photo.jpg', {
title: 'My Photo',
description: 'A beautiful sunset'
});
// Get and set title
const title = await sirv.getFileTitle('/images/photo.jpg');
await sirv.setFileTitle('/images/photo.jpg', 'New Title');
// Manage tags
const tags = await sirv.getFileTags('/images/photo.jpg');
await sirv.addFileTags('/images/photo.jpg', ['nature', 'sunset', 'beach']);
await sirv.removeFileTags('/images/photo.jpg', ['beach']);
// Set product metadata
await sirv.setProductMeta('/images/product.jpg', {
id: 'SKU123',
name: 'Product Name',
brand: 'Brand Name'
});
// Approval flag
const approved = await sirv.getApprovalFlag('/images/photo.jpg');
await sirv.setApprovalFlag('/images/photo.jpg', true);
// Create ZIP file
const zipResult = await sirv.batchZip({
filenames: ['/images/photo1.jpg', '/images/photo2.jpg'],
zipFilename: 'my-archive.zip'
});
console.log('ZIP URL:', zipResult.url);
// Fetch file from URL
await sirv.fetchUrl({
url: 'https://example.com/image.jpg',
filename: '/images/fetched-image.jpg'
});
// Get folder options
const options = await sirv.getFolderOptions('/images');
// Set folder options
await sirv.setFolderOptions('/images', {
scanSpins: true
});

Manage your Sirv account settings and retrieve account information.

MethodDescription
getAccountInfo()Get account information including CDN URL and account name
updateAccount(options)Update account settings (minify, fetching)
getAccountLimits()Get API request limits and usage
getStorageInfo()Get storage usage information
getAccountUsers()List all account users
getBillingPlan()Get billing plan details
// Get account information
const account = await sirv.getAccountInfo();
console.log('CDN URL:', account.cdnURL);
// Get API limits
const limits = await sirv.getAccountLimits();
console.log(`API calls: ${limits.used}/${limits.limit}`);
// Get storage information
const storage = await sirv.getStorageInfo();
console.log(`Storage used: ${storage.used} bytes`);
// Get billing plan
const plan = await sirv.getBillingPlan();
console.log('Plan:', plan.name);
// List account users
const users = await sirv.getAccountUsers();

Retrieve usage statistics for your account.

MethodDescription
getHttpStats(params)Get HTTP transfer statistics
getSpinViewsStats(params)Get spin viewer statistics
getStorageStats(params)Get storage statistics
// HTTP transfer statistics
const httpStats = await sirv.getHttpStats({
from: '2024-01-01',
to: '2024-01-31'
});
// Spin views statistics
const spinStats = await sirv.getSpinViewsStats({
from: '2024-01-01',
to: '2024-01-05' // Max 5 days
});
// Storage statistics
const storageStats = await sirv.getStorageStats({
from: '2024-01-01',
to: '2024-01-31'
});

Convert between spin and video formats, and manage points of interest.

// Convert spin to video
const video = await sirv.spin2Video({
filename: '/spins/product.spin'
});
// Convert video to spin
const spin = await sirv.video2Spin({
filename: '/videos/product.mp4'
});
// Export spin for marketplaces
await sirv.exportSpinToAmazon({ filename: '/spins/product.spin' });
await sirv.exportSpinToWalmart({ filename: '/spins/product.spin' });
// Get points of interest
const pois = await sirv.getPointsOfInterest('/spins/product.spin');
// Set point of interest
await sirv.setPointOfInterest('/spins/product.spin', {
name: 'Feature Highlight',
frame: 10,
x: 0.5,
y: 0.3
});
// Delete point of interest
await sirv.deletePointOfInterest('/spins/product.spin', 'poi-id');

Generate protected access tokens for secure file access.

const jwt = await sirv.generateJwt({
filename: '/images/private-photo.jpg',
expiresIn: 3600 // 1 hour
});
console.log('Protected URL:', jwt.url);

The SDK provides a SirvApiError class for API-specific exceptions.

import { SirvClient, SirvApiError } from '@sirv/rest-api-js';
try {
const sirv = new SirvClient({
clientId: 'client-id',
clientSecret: 'client-secret'
});
await sirv.uploadFile('/images/photo.jpg', fileBuffer);
} catch (error) {
if (error instanceof SirvApiError) {
console.error('Status:', error.statusCode);
console.error('Error code:', error.errorCode);
console.error('Message:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
PropertyDescription
statusCodeHTTP status code
errorCodeSirv-specific error code
messageError message

The SDK includes full TypeScript type definitions for all methods and responses.

import { SirvClient, SirvClientConfig, AccountInfo, FileInfo } from '@sirv/rest-api-js';
const config: SirvClientConfig = {
clientId: 'your-client-id',
clientSecret: 'your-client-secret'
};
const sirv = new SirvClient(config);
const account: AccountInfo = await sirv.getAccountInfo();
const fileInfo: FileInfo = await sirv.getFileInfo('/images/photo.jpg');

The SDK exports interfaces for:

  • Configuration (SirvClientConfig)
  • Account data (AccountInfo, StorageInfo, BillingPlan)
  • Files (FileInfo, FolderContents, SearchResult)
  • Spins (SpinInfo, PointOfInterest)
  • Statistics (HttpStats, SpinViewsStats, StorageStats)
  • Errors (SirvApiError)

The SDK works across multiple environments:

EnvironmentSupport
Node.js✅ Full support (v16+)
Browser✅ Full support (ES6+)
TypeScript✅ Full type definitions
  • Automatic token management with refresh
  • Async iterators for pagination
  • Retry logic with exponential backoff
  • Cross-platform compatibility
Back to top