easyCDN Logo

Node.js SDK API Reference

Complete API reference for the easyCDN Node.js SDK, including all methods, options, and TypeScript types.

createClient()

Initialize a new easyCDN API client for Node.js applications. This is the entry point for all server-side operations.

Signature

typescript
import { createClient } from '@easycdn/server'

createClient(options: {
  secretKey: string
  baseUrl?: string
}): ApiClient

Example: Basic initialization

typescript
import { createClient } from '@easycdn/server'

const client = createClient({
  secretKey: process.env.EASYCDN_SECRET_KEY
})

Parameters

secretKey:stringrequired - Your easyCDN API secret key
baseUrl:string - Custom API base URL (defaults to production)

Returns

Returns an ApiClient instance with methods for uploading and managing assets

upload():function - Upload files to easyCDN
persist():function - Persist temporary assets
uploadFromOpenAi():function - Upload images from OpenAI/xAI responses
healthCheck():function - Check API health status

persist()

Persist a temporary asset to permanent storage. This finalizes an uploaded file and makes it permanently accessible via CDN. Optionally apply transformations like resizing, format conversion, and quality adjustments.

Signature

typescript
persist(
  input: {
    tempAssetId: string
    transform?: {
      image?: {
        width?: number
        height?: number
        quality?: number
        format?: 'webp' | 'jpeg' | 'png'
      }
    }
    expiresAt?: string
    fileName?: string
  }
): Promise<{ asset: Asset }>

Example: Basic persist

typescript
const result = await client.persist({
  tempAssetId: 'temp-asset-id-123'
})
console.log(result.asset.url) // CDN URL

Example: Persist with image transformation

typescript
const result = await client.persist({
  tempAssetId: 'temp-asset-id-123',
  transform: {
    image: {
      width: 800,
      height: 600,
      quality: 85,
      format: 'webp'
    }
  }
})

Example: Persist with expiration

typescript
const expirationDate = new Date()
expirationDate.setDate(expirationDate.getDate() + 7) // Expires in 7 days

const result = await client.persist({
  tempAssetId: 'temp-asset-id-123',
  expiresAt: expirationDate.toISOString(),
  fileName: 'my-custom-name.jpg'
})

Parameters

tempAssetId:stringrequired - The ID of the temporary asset to persist
transform:optional - Optional transformations to apply
expiresAt:string - Format: ISO datetime - Optional expiration date
fileName:string - Custom filename for the asset

Returns

Returns the persisted asset with CDN URL

asset: - The persisted asset

upload()

Upload a file to easyCDN from a file path, Buffer, or stream. This method handles multipart uploads automatically for large files and provides progress tracking. The file is automatically persisted after upload.

Signature

typescript
upload(
  source: string | Buffer | ReadableStream,
  options?: {
    fileName?: string
    onProgress?: (progress: UploadProgress) => void
    transform?: {
      image?: {
        width?: number
        height?: number
        quality?: number
        format?: 'webp' | 'jpeg' | 'png'
      }
    }
    expiresAt?: string
    chunkSize?: number
  }
): Promise<{ asset: Asset }>

Example: Upload from file path

typescript
const result = await client.upload('/path/to/file.jpg')
console.log(result.asset.url)

Example: Upload with progress tracking

typescript
const result = await client.upload('/path/to/large-file.mp4', {
  onProgress: (progress) => {
    console.log(`Progress: ${progress.percentage}%`)
  }
})

Example: Upload Buffer with transformation

typescript
const buffer = fs.readFileSync('/path/to/image.png')
const result = await client.upload(buffer, {
  fileName: 'my-image.webp',
  transform: {
    image: {
      width: 1200,
      format: 'webp',
      quality: 90
    }
  }
})

Example: Upload with custom chunk size

typescript
const result = await client.upload('/path/to/file.zip', {
  chunkSize: 10 * 1024 * 1024, // 10MB chunks
  fileName: 'archive.zip'
})

Parameters

source:string | Buffer | ReadableStreamrequired - File path, Buffer, or stream to upload
options:object
fileName:string - Custom filename for the asset
onProgress:(progress: UploadProgress) => void - Callback for upload progress
transform: - Optional transformations to apply
expiresAt:string - Format: ISO datetime - Optional expiration date
chunkSize:number - Chunk size for multipart uploads (in bytes)

Returns

Returns the uploaded and persisted asset with CDN URL

asset: - The uploaded and persisted asset

uploadFromOpenAi()

Upload images generated by OpenAI or xAI directly to easyCDN. Automatically downloads images from OpenAI URLs or base64 data and uploads them. Supports both single and batch image generation responses.

Signature

typescript
uploadFromOpenAi(
  response: ImagesResponse | OpenAI.Responses.Response | any,
  options?: {
    fileNames?: string[]
    fileNamePrefix?: string
    onProgress?: (progress: UploadProgress) => void
    transform?: {
      image?: {
        width?: number
        height?: number
        quality?: number
        format?: 'webp' | 'jpeg' | 'png'
      }
    }
    expiresAt?: string
  }
): Promise<Array<{ asset: Asset }>>

Example: Upload OpenAI generated image

typescript
import OpenAI from 'openai'
import createClient from '@easycdn/server'

const openai = new OpenAI({ apiKey: 'your-openai-key' })
const client = createClient({ secretKey: 'your-easycdn-key' })

const response = await openai.images.generate({
  model: 'dall-e-3',
  prompt: 'A sunset over mountains',
  n: 1,
  size: '1024x1024'
})

const assets = await client.uploadFromOpenAi(response)
console.log(assets[0].asset.url) // CDN URL

Example: Upload with transformation

typescript
const response = await openai.images.generate({
  model: 'dall-e-3',
  prompt: 'Abstract art',
  n: 1
})

const assets = await client.uploadFromOpenAi(response, {
  transform: {
    image: {
      format: 'webp',
      quality: 85
    }
  },
  fileName: 'ai-generated-art.webp'
})

Parameters

response:ImagesResponse | OpenAI.Responses.Response | anyrequired - OpenAI or xAI image generation response
options:object
fileNames:string[] - Custom filenames for each generated image
fileNamePrefix:string - Prefix for auto-generated filenames
onProgress:(progress: UploadProgress) => void - Callback for upload progress
transform: - Optional transformations to apply
expiresAt:string - Format: ISO datetime - Optional expiration date

Returns

Returns array of uploaded assets with CDN URLs (one per generated image)

assets:Array<object> - Array of uploaded assets (one per generated image)
asset: - The uploaded asset

uploadFromGoogleAi()

Upload images generated by Google Gemini directly to easyCDN. Automatically extracts base64 image data from the response and uploads them. Supports both single and multi-image generation responses.

Signature

typescript
uploadFromGoogleAi(
  response: GenerateContentResponse | any,
  options?: {
    fileNames?: string[]
    fileNamePrefix?: string
    onProgress?: (progress: UploadProgress) => void
    transform?: {
      image?: {
        width?: number
        height?: number
        quality?: number
        format?: 'webp' | 'jpeg' | 'png'
      }
    }
    expiresAt?: string
  }
): Promise<Array<{ asset: Asset }>>

Example: Upload Google AI generated image

typescript
import { GoogleGenAI } from '@google/genai'
import { createClient } from '@easycdn/server'

const ai = new GoogleGenAI({ apiKey: 'your-google-key' })
const client = createClient({ secretKey: 'your-easycdn-key' })

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash-image',
  contents: 'A sunset over mountains',
  config: { responseModalities: ['Text', 'Image'] },
})

const assets = await client.uploadFromGoogleAi(response)
console.log(assets[0].asset.url) // CDN URL

Example: Upload with transformation

typescript
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash-image',
  contents: 'Abstract art',
  config: { responseModalities: ['Text', 'Image'] },
})

const assets = await client.uploadFromGoogleAi(response, {
  fileNamePrefix: 'gemini-art',
  transform: {
    image: {
      format: 'webp',
      quality: 85
    }
  }
})

Parameters

response:GenerateContentResponse | anyrequired - Google GenAI image generation response
options:object
fileNames:string[] - Custom filenames for each generated image
fileNamePrefix:string - Prefix for auto-generated filenames
onProgress:(progress: UploadProgress) => void - Callback for upload progress
transform: - Optional transformations to apply
expiresAt:string - Format: ISO datetime - Optional expiration date

Returns

Returns array of uploaded assets with CDN URLs (one per generated image)

assets:Array<object> - Array of uploaded assets (one per generated image)
asset: - The uploaded asset

TransformOptions

Options for transforming assets during upload or persist operations. Currently supports image transformations including resizing, format conversion, and quality adjustments.

Properties

image:objectoptional - Image transformation options
width:number - Target width in pixels
height:number - Target height in pixels
quality:number - Image quality (1-100)
format:'webp' | 'jpeg' | 'png' - Output format

Asset

Represents an uploaded asset in the easyCDN system with all its metadata and properties. This type is returned by upload and persist operations.

Properties

_id:string - Unique identifier for the asset
url:string - Public CDN URL for accessing the asset
name:string - Filename of the asset, as displayed in the easyCDN dashboard
size:number - File size in bytes
type:string - MIME type of the asset
expiresAt:string | null - Format: ISO datetime - Optional expiration date for the asset
projectId:string - ID of the project this asset belongs to
createdAt:string - Format: ISO datetime - When the asset was created
updatedAt:string - Format: ISO datetime - When the asset was last updated
bucket:string - Storage bucket where the asset is stored
key:string - Storage key/path for the asset
userId:string - ID of the user who uploaded the asset