JavaScript SDK for Sirv REST API
npm install @sirv/rest-api-js2. Copy your Client ID and Client secret from Account › Settings › API.3. Connectimport { SirvClient } from '@sirv/rest-api-js';
const sirv = new SirvClient({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
}); No account yet? Create one freeShort 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:
Installation
Section titled “Installation”Install the SDK via npm or yarn:
npm install @sirv/rest-api-jsyarn add @sirv/rest-api-jsBrowser Usage
Section titled “Browser Usage”For browser environments, include via CDN:
<script src="https://unpkg.com/@sirv/rest-api-js/dist/sirv.min.js"></script>Requirements
Section titled “Requirements”- Node.js 16 or higher (for Node.js environments)
- Modern browser with ES6 support (for browser environments)
Quick Start
Section titled “Quick Start”import { SirvClient } from '@sirv/rest-api-js';
// Initialize the clientconst sirv = new SirvClient({ clientId: 'your-client-id', clientSecret: 'your-client-secret'});
// Get account informationconst account = await sirv.getAccountInfo();console.log('Account:', account.alias);
// List files in a directoryconst files = await sirv.readFolderContents('/');for (const file of files.contents) { console.log(file.filename);}Authentication
Section titled “Authentication”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 credentialstry { await sirv.connect(); console.log('Authenticated successfully');} catch (error) { console.error('Authentication failed:', error.message);}
// Check if connectedif (sirv.isConnected()) { console.log('Token is valid');}
// Get current access tokenconst token = sirv.getAccessToken();Configuration Options
Section titled “Configuration Options”| Option | Type | Default | Description |
|---|---|---|---|
clientId | string | required | Your API client ID |
clientSecret | string | required | Your API client secret |
baseUrl | string | https://api.sirv.com | API endpoint |
autoRefreshToken | boolean | true | Auto-refresh token before expiry |
timeout | number | 30000 | Request timeout in milliseconds |
maxRetries | number | 3 | Retry failed requests with exponential backoff |
Files API
Section titled “Files API”Complete file management including upload, download, copy, rename, delete, and metadata operations.
Available Methods
Section titled “Available Methods”| Category | Methods |
|---|---|
| File Operations | readFolderContents(), getFileInfo(), uploadFile(), downloadFile(), copyFile(), renameFile(), deleteFile(), batchDelete(), createFolder(), fetchUrl() |
| Metadata | getFileMeta(), setFileMeta(), getApprovalFlag(), setApprovalFlag(), getFileTitle(), setFileTitle(), getFileDescription(), setFileDescription(), getProductMeta(), setProductMeta(), getFileTags(), addFileTags(), removeFileTags() |
| Batch Operations | batchZip(), batchDelete() |
| Media & Export | spin2Video(), video2Spin(), exportSpinToAmazon(), exportSpinToWalmart(), exportSpinToHomeDepot(), exportSpinToLowes(), exportSpinToGrainger() |
Basic Operations
Section titled “Basic Operations”// List folder contentsconst files = await sirv.readFolderContents('/images');
// Upload a file (supports paths, buffers, streams)await sirv.uploadFile('/images/photo.jpg', fileBuffer);
// Upload with optionsawait sirv.uploadFile('/images/photo.jpg', fileBuffer, { contentType: 'image/jpeg'});
// Download a fileconst data = await sirv.downloadFile('/images/photo.jpg');
// Copy a fileawait sirv.copyFile({ from: '/images/photo.jpg', to: '/backup/photo.jpg'});
// Rename/move a fileawait sirv.renameFile({ from: '/images/old-name.jpg', to: '/images/new-name.jpg'});
// Delete a fileawait sirv.deleteFile('/images/photo.jpg');
// Delete multiple filesawait sirv.batchDelete(['/images/photo1.jpg', '/images/photo2.jpg']);
// Create a folderawait sirv.createFolder('/images/new-folder');Search Files
Section titled “Search Files”// Search filesconst results = await sirv.searchFiles({ query: 'filename:*.jpg', from: '/images', size: 100});
// Auto-paginating search iteratorfor await (const file of sirv.iterateSearchResults({ query: 'extension:.jpg', from: '/images'})) { console.log(file.filename);}Folder Iteration
Section titled “Folder Iteration”// Auto-paginating folder contents iteratorfor await (const item of sirv.iterateFolderContents('/images')) { console.log(item.filename);}Metadata Operations
Section titled “Metadata Operations”// Get and set file metadataconst meta = await sirv.getFileMeta('/images/photo.jpg');await sirv.setFileMeta('/images/photo.jpg', { title: 'My Photo', description: 'A beautiful sunset'});
// Get and set titleconst title = await sirv.getFileTitle('/images/photo.jpg');await sirv.setFileTitle('/images/photo.jpg', 'New Title');
// Manage tagsconst 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 metadataawait sirv.setProductMeta('/images/product.jpg', { id: 'SKU123', name: 'Product Name', brand: 'Brand Name'});
// Approval flagconst approved = await sirv.getApprovalFlag('/images/photo.jpg');await sirv.setApprovalFlag('/images/photo.jpg', true);Batch Operations
Section titled “Batch Operations”// Create ZIP fileconst zipResult = await sirv.batchZip({ filenames: ['/images/photo1.jpg', '/images/photo2.jpg'], zipFilename: 'my-archive.zip'});console.log('ZIP URL:', zipResult.url);
// Fetch file from URLawait sirv.fetchUrl({ url: 'https://example.com/image.jpg', filename: '/images/fetched-image.jpg'});Folder Options
Section titled “Folder Options”// Get folder optionsconst options = await sirv.getFolderOptions('/images');
// Set folder optionsawait sirv.setFolderOptions('/images', { scanSpins: true});Account API
Section titled “Account API”Manage your Sirv account settings and retrieve account information.
Available Methods
Section titled “Available Methods”| Method | Description |
|---|---|
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 |
Examples
Section titled “Examples”// Get account informationconst account = await sirv.getAccountInfo();console.log('CDN URL:', account.cdnURL);
// Get API limitsconst limits = await sirv.getAccountLimits();console.log(`API calls: ${limits.used}/${limits.limit}`);
// Get storage informationconst storage = await sirv.getStorageInfo();console.log(`Storage used: ${storage.used} bytes`);
// Get billing planconst plan = await sirv.getBillingPlan();console.log('Plan:', plan.name);
// List account usersconst users = await sirv.getAccountUsers();Statistics API
Section titled “Statistics API”Retrieve usage statistics for your account.
| Method | Description |
|---|---|
getHttpStats(params) | Get HTTP transfer statistics |
getSpinViewsStats(params) | Get spin viewer statistics |
getStorageStats(params) | Get storage statistics |
// HTTP transfer statisticsconst httpStats = await sirv.getHttpStats({ from: '2024-01-01', to: '2024-01-31'});
// Spin views statisticsconst spinStats = await sirv.getSpinViewsStats({ from: '2024-01-01', to: '2024-01-05' // Max 5 days});
// Storage statisticsconst storageStats = await sirv.getStorageStats({ from: '2024-01-01', to: '2024-01-31'});Spins & 360 Views
Section titled “Spins & 360 Views”Convert between spin and video formats, and manage points of interest.
// Convert spin to videoconst video = await sirv.spin2Video({ filename: '/spins/product.spin'});
// Convert video to spinconst spin = await sirv.video2Spin({ filename: '/videos/product.mp4'});
// Export spin for marketplacesawait sirv.exportSpinToAmazon({ filename: '/spins/product.spin' });await sirv.exportSpinToWalmart({ filename: '/spins/product.spin' });
// Get points of interestconst pois = await sirv.getPointsOfInterest('/spins/product.spin');
// Set point of interestawait sirv.setPointOfInterest('/spins/product.spin', { name: 'Feature Highlight', frame: 10, x: 0.5, y: 0.3});
// Delete point of interestawait sirv.deletePointOfInterest('/spins/product.spin', 'poi-id');JWT Generation
Section titled “JWT Generation”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);Error Handling
Section titled “Error Handling”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); }}SirvApiError Properties
Section titled “SirvApiError Properties”| Property | Description |
|---|---|
statusCode | HTTP status code |
errorCode | Sirv-specific error code |
message | Error message |
TypeScript Support
Section titled “TypeScript Support”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');Exported Types
Section titled “Exported Types”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)
Platform Compatibility
Section titled “Platform Compatibility”The SDK works across multiple environments:
| Environment | Support |
|---|---|
| Node.js | ✅ Full support (v16+) |
| Browser | ✅ Full support (ES6+) |
| TypeScript | ✅ Full type definitions |
Features
Section titled “Features”- Automatic token management with refresh
- Async iterators for pagination
- Retry logic with exponential backoff
- Cross-platform compatibility
