@pixozip/sdk
v0.1.2
Published
Node.js SDK for pixozip — image optimization API
Downloads
422
Readme
@pixozip/sdk
The official dependency-free Node.js SDK for Pixozip — a high-performance image optimization, resizing, and conversion API. Speed up your web applications, improve SEO PageSpeed metrics, and reduce CDN/S3 storage costs by compressing images up to 90% without visible quality loss.
✨ Features
- 🚀 Zero Dependencies — Built entirely on native Node fetch and streams for minimal bundle footprint.
- ⚡ Type Safe — Full TypeScript definitions out of the box.
- 🔄 Smart Retries — Automatic exponential backoff for network glitched requests (idempotent 429 and 5xx errors).
- 🖼️ Modern Formats — Supports standard conversion to
webp,avif,jxl, or automatic detection. - 📐 Dynamic Resizing — Downscale images dynamically using customizable fit presets.
- ⏱️ Async Support — Supports asynchronous queue processing for batch or heavy image payloads.
📦 Installation
Install the package via your preferred package manager:
# npm
npm install @pixozip/sdk
# yarn
yarn add @pixozip/sdk
# pnpm
pnpm add @pixozip/sdk🚀 Quick Start
Here is a simple example showing how to optimize a local JPEG image and save the result:
import { Pixozip } from "@pixozip/sdk";
import * as fs from "fs/promises";
async function optimizeImage() {
// Initialize client (reads key from configuration)
const zip = new Pixozip({
apiKey: process.env.PIXOZIP_API_KEY || "your_api_key_here"
});
// Load the raw image buffer
const imageBuffer = await fs.readFile("original-photo.jpg");
try {
// Compress and convert to modern WebP
const result = await zip.shrink(imageBuffer, {
contentType: "image/jpeg",
output: "webp",
qualityTier: "balanced"
});
console.log(`Job ID: ${result.jobId}`);
console.log(`Original size: ${imageBuffer.length} bytes`);
console.log(`Optimized size: ${result.outputBytes} bytes`);
console.log(`Reduction: ${Math.round((1 - (result.ratio ?? 1)) * 100)}%`);
// Download the optimized bytes using helper
const optimizedBytes = await result.download();
// Save to disk
await fs.writeFile("optimized-photo.webp", optimizedBytes);
console.log("Image saved successfully!");
} catch (error) {
console.error("Optimization failed:", error);
}
}
optimizeImage();⚙️ Configuration & Options
Client Initialization Options
Pass these options to the new Pixozip(options) constructor:
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| apiKey | string | Required | Your Pixozip API Key from developer dashboard. |
| baseUrl | string | "https://api.pixozip.com" | Gateway endpoint URL. |
| maxRetries | number | 3 | Number of automated retries on rate limits (429) or transient 5xx failures. |
| retryBaseDelayMs | number | 500 | Initial delay for retry backoff. |
| defaultTimeoutMs | number | 60000 | Global network request timeout in milliseconds. |
Shrink Configuration Options
Pass these options to the client.shrink(buffer, options) method:
| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| contentType | string | Yes | MIME type of input image (e.g. image/jpeg, image/png). |
| output | string | No | Target format: "auto", "webp", "avif", "jpeg", "png", "jxl". |
| quality | number | No | Manual quality factor (1-100). |
| qualityTier | string | No | Quality preset: "fast", "balanced", "max". |
| resize | object | No | Image dimensions scaling configuration (see below). |
| lossless | boolean | No | If true, applies strict pixel-perfect compression. |
| keepMetadata | boolean | No | If true, preserves EXIF, ICC Profiles, and GPS headers. |
| async | boolean | No | If true, returns immediately with a jobId without waiting for processing. |
| idempotencyKey | string | No | Unique transaction key to prevent charge double-billing on network retries. |
Resize Parameters
resize?: {
width?: number;
height?: number;
fit?: "cover" | "contain" | "fill" | "inside" | "outside";
}⏳ Asynchronous Processing (Queues)
For batch imports or slow processing tasks, enable the async option to avoid keeping HTTP connections open. The API will respond instantly with a jobId, which you can poll dynamically:
const result = await zip.shrink(imageBuffer, {
contentType: "image/jpeg",
async: true
});
console.log(`Job queued with ID: ${result.jobId}`);
// Poll status until completed
let job = result;
while (job.status === "queued" || job.status === "processing") {
await new Promise((resolve) => setTimeout(resolve, 1000));
job = await zip.getJob(result.jobId);
}
if (job.status === "completed") {
const bytes = await job.download();
await fs.writeFile("output.jpg", bytes);
console.log("Async job done!");
} else {
console.error("Job failed or was cancelled:", job.status);
}❌ Error Handling
All failed operations throw a PixozipError which holds the status code and error messages returned by the API gateway:
import { Pixozip, PixozipError } from "@pixozip/sdk";
try {
await zip.shrink(badBuffer, { contentType: "image/png" });
} catch (error) {
if (error instanceof PixozipError) {
console.error(`HTTP Status: ${error.status}`);
console.error("Gateway response:", error.body);
// error.body structure: { error: "rate_limit_exceeded", message: "..." }
} else {
console.error("Generic network error:", error);
}
}📄 License
MIT © Pixozip
