@creativekit/client
v1.0.42
Published
Browser-safe CreativeKit SDK (no secrets required)
Maintainers
Readme
@creativekit/client
Browser-safe CreativeKit SDK using presigned URLs
✅ No credentials needed - talks to YOUR backend only
Quick Start
npm install @creativekit/clientimport { CreativeKitClient } from "@creativekit/client";
const client = new CreativeKitClient({
backendUrl: "/api/creatives", // YOUR backend, not CreativeKit API
});
// Upload a file with progress tracking
const result = await client.upload(file, "audio:podcast-aac", (progress) => {
console.log(`${progress.progress.toFixed(1)}% - ${progress.message}`);
});
console.log("Creative:", result.id, result.status);
// Status values are UPPERCASE: "AWAITING_UPLOAD" | "QUEUED" | "PROCESSING" | "SUCCEEDED" | "FAILED" | "CANCELED"How It Works
1. Client → Your Backend: "Give me upload URL"
2. Your Backend → CreativeKit API: Create creative (using server SDK)
3. Client → Storage: Upload directly to presigned URL
4. Client → Your Backend: "Commit creative" (triggers processing)
5. Client polls or streams SSE for completionYour backend needs these endpoints (each is a thin proxy to the matching @creativekit/server method):
Routes are grouped under three configurable bases — backendUrl (creatives),
profilesUrl, and bundlesUrl — so each resource stays top-level on your
backend (no nesting profiles under creatives).
| Endpoint (relative to base) | Base | Server SDK call | Used by |
| ---------------------------------------------- | ------------- | --------------------------------------- | -------------------------------- |
| POST {backendUrl} | backendUrl | ck.creatives.create(profile, opts) | upload, uploadMultiple |
| GET {backendUrl} | backendUrl | ck.creatives.list(filters) | listCreatives |
| POST {backendUrl}/:id/commit | backendUrl | ck.creatives.commit(id, body) | upload, uploadMultiple |
| GET {backendUrl}/:id | backendUrl | ck.creatives.get(id) | getCreative, polling |
| GET {backendUrl}/:id/events | backendUrl | ck.creatives.getEventsStream(id, res) | streamEvents (optional) |
| POST {backendUrl}/:id/finalize | backendUrl | ck.creatives.finalize(id) | finalize |
| POST {backendUrl}/:id/preview | backendUrl | ck.creatives.preview(id) | preview |
| PATCH {backendUrl}/:id | backendUrl | ck.creatives.cancel(id) / retry(id) | cancel, retry |
| DELETE {backendUrl}/:id | backendUrl | ck.creatives.delete(id) | delete |
| POST {backendUrl}/:id/slots/:slot/reopen | backendUrl | ck.creatives.reopenSlot(id, slot) | replaceSlot, requestSlotReopen |
| POST {backendUrl}/:id/slots/:slot/replace | backendUrl | ck.creatives.replaceSlot({ id, slot })| replaceSlot, commitSlotReplacement |
| POST {backendUrl}/:id/clone | backendUrl | ck.creatives.clone(id) | clone |
| GET {profilesUrl} | profilesUrl | ck.profiles.list() | listProfiles |
| POST {profilesUrl}/:id/validate | profilesUrl | ck.profiles.validateMetadata(id, body)| validateMetadata |
| GET {bundlesUrl} | bundlesUrl | ck.profiles.listBundles() | listBundles |
| GET {bundlesUrl}/:id | bundlesUrl | ck.profiles.getBundle(id) | getBundle |
All endpoints proxy
@creativekit/server. The browser client never holds credentials — every method above hits your backend, which authenticates the request and forwards it to the API. Because of that, lifecycle actions (cancel,retry,delete) are available on the client too, but your backend proxy is responsible for authorizing who may call them.Backward compatible:
profilesUrl/bundlesUrlare optional and default to${backendUrl}/profilesand${backendUrl}/bundles, so existing single-base setups keep working unchanged.
Configuration
const client = new CreativeKitClient({
// Required: base URL for the creatives resource
backendUrl: "/api/creatives",
// Optional: dedicated bases for the profile registry + bundles.
// Default to `${backendUrl}/profiles` and `${backendUrl}/bundles` if omitted.
profilesUrl: "/api/profiles",
bundlesUrl: "/api/bundles",
// Optional: extra headers for every backend request (e.g. auth tokens)
getHeaders: () => ({ Authorization: `Bearer ${getToken()}` }),
// Optional: fetch credentials mode for backend requests
// "include" (default) | "same-origin" | "omit"
credentials: "omit",
});credentials controls whether cookies are sent with backend requests, and also sets withCredentials on the SSE connection (true only for "include"). Use the default "include" for cookie-based auth — your backend must then respond with a specific Access-Control-Allow-Origin (not *) and Access-Control-Allow-Credentials: true. Use "omit" with token-based auth via getHeaders when your backend serves Access-Control-Allow-Origin: *, since browsers reject the * wildcard for credentialed requests.
API Reference
Upload Methods
// Simple upload (handles everything automatically)
// Includes: request URL → upload → commit → wait for completion
const result = await client.upload(file, profile, onProgress);
// Manual control (advanced)
const request = await client.requestUpload(profile, {
fileName: file.name, // Optional: original filename
fileSize: file.size, // Optional: file size in bytes
contentType: file.type, // Optional: MIME type
});
await client.uploadFile(
request.uploadUrl,
file,
request.uploadHeaders,
(loaded, total) => console.log(`${loaded}/${total} bytes`), // Optional progress
);
await client.commit(request.creativeId); // IMPORTANT: Must call to start processing
// Cancel an in-progress upload
client.cancelUpload();Multi-Slot & Carousel Uploads
Profiles with multiple slots (e.g. the native ad pack's standard + large)
or dynamic slots (carousel frame_1…frame_N) use uploadMultiple. Pass
slotCounts for dynamic profiles and optional slotTransforms to crop per slot.
// Native ad pack — one file per named slot
const native = await client.uploadMultiple(
{ standard: standardFile, large: largeFile },
"native:image",
(p) => console.log(`${p.progress.toFixed(0)}%`),
// crop is in SOURCE pixels; target is the output resolution after crop+scale
{ slotTransforms: { standard: { aspectRatio: "1.91:1", cropX: 0, cropY: 0, cropW: 1200, cropH: 628, targetWidth: 1200, targetHeight: 628 } } },
);
// Carousel — slotCounts expands the dynamic `frame` slot
const carousel = await client.uploadMultiple(
{ frame_1: f1, frame_2: f2, frame_3: f3 },
"native:carousel",
undefined,
{ slotCounts: { frame: 3 } },
);Editing a Creative (Replace One Slot)
Swap a single slot/frame of an existing draft creative (must be SUCCEEDED
or FAILED and not finalized) without recreating it. replaceSlot runs the
full reopen → upload → reprocess → wait flow against your backend's
/reopen and /replace proxy routes.
// Replace one carousel frame and wait for reprocessing to finish
const updated = await client.replaceSlot(
creativeId,
"frame_2",
newImageFile,
(p) => console.log(`${p.stage}: ${p.progress.toFixed(0)}%`),
);
// Lower-level building blocks (if you manage upload yourself):
const { uploadSlots } = await client.requestSlotReopen(creativeId, "frame_2");
await client.uploadFile(uploadSlots[0].url, newImageFile, uploadSlots[0].headers);
await client.commitSlotReplacement(creativeId, "frame_2");Editing a Finalized Creative (Clone)
Finalized creatives are immutable. To "edit" one — e.g. change 4 of 8 carousel
frames — clone it into a fresh draft. The backend server-side copies every
raw upload, so the clone arrives with all slots already seeded from the
original; upload new files only for the slots you change, then commit +
finalize. The result is a brand-new finalized creative (new ID/URL); the
original is never touched.
// 1) Clone → new draft seeded with the original's frames
const { creativeId, uploadSlots } = await client.clone(finalizedId);
// 2) Upload only the slots the user changed (e.g. frame_2, frame_5)
for (const slot of changedSlots) {
const target = uploadSlots.find((s) => s.name === slot)!;
await client.uploadFile(target.url, newFiles[slot], target.headers);
}
// 3) Commit reprocesses all slots from raw, then finalize
await client.commit(creativeId);
await client.finalize(creativeId);To remove or reorder carousel slides (not just replace their content), pass
slotPlan on clone. Each entry lists which source slots seed the new positions
in order; omit frames you want dropped.
// 5-frame carousel → keep frames 1, 3, 5 (drops 2 and 4)
const { creativeId, uploadSlots } = await client.clone(finalizedId, {
slotPlan: { frame: ["frame_1", "frame_3", "frame_5"] },
});
// uploadSlots = [frame_1, frame_2, frame_3] seeded from source frame_1, frame_3, frame_5
await client.commit(creativeId);
await client.finalize(creativeId);Use an empty string in slotPlan for a blank position the user must upload
before commit (e.g. { frame: ["frame_1", "", "frame_3"] }).
Status & Monitoring
// Get creative status and artifacts
const creative = await client.getCreative(id);
// Status values: "AWAITING_UPLOAD" | "QUEUED" | "PROCESSING" | "SUCCEEDED" | "FAILED" | "CANCELED"
// AWAITING_UPLOAD = waiting for file upload + commit (rare in client flow)
// Progress is 0.0-1.0 (multiply by 100 for percentage)
// Stream live status updates via SSE
// NOTE: Stream auto-closes on terminal states (SUCCEEDED, FAILED, CANCELED)
const stream = client.streamEvents(creativeId, {
onUpdate: (update) => {
// update.progress is 0.0-1.0, multiply by 100 for percentage
console.log(`Status: ${update.status}, Progress: ${update.progress * 100}%`);
},
onError: (error) => console.error("Stream error:", error),
onClose: () => console.log("Stream closed"),
});
// Manual close if needed
stream.close();
// Check stream status
console.log(stream.closed); // booleanLifecycle Management
// Finalize a creative (mark as permanent, prevent auto-cleanup)
await client.finalize(creativeId);
// List creatives with optional filters + pagination
const { items, nextPageToken } = await client.listCreatives({
status: "SUCCEEDED",
profile: "native:image",
finalized: true,
limit: 20,
});
// Generate a fresh signed preview URL for a completed creative
const { url } = await client.preview(creativeId);
// Control processing
await client.cancel(creativeId); // cancel an in-flight creative
await client.retry(creativeId); // retry a FAILED creative
// Delete a creative and its artifacts
await client.delete(creativeId);
// List available processing profiles
const profiles = await client.listProfiles();
// Returns: Profile[] with id, type, description, etc.
// List profile bundles (e.g. the native ad pack: standard + large)
const bundles = await client.listBundles({ expandProfiles: true });
// Get a single bundle by id
const bundle = await client.getBundle("native:standard", { expandProfiles: true });Pre-upload Validation
Validate declared file metadata against a profile before uploading bytes —
useful for instant client-side feedback. Returns the same { errors, warnings }
shapes the pipeline emits, namespaced per slot.
const result = await client.validateMetadata("native:image", {
slots: {
standard: { mimeType: "image/png", sizeBytes: 1_048_576, width: 1200, height: 628 },
},
});
if (!result.passed) {
console.log(result.errors); // e.g. [{ field: "standard.aspectRatio", message: "..." }]
}This is advisory — the authoritative validation still runs on the real bytes after upload.
Progress Tracking
interface UploadProgress {
stage:
| "preparing" // Requesting upload URL
| "uploading" // Uploading to presigned URL
| "committing" // Committing upload
| "processing" // Server processing
| "complete" // Done successfully
| "failed"; // Error occurred
progress: number; // 0-100 (canonical field, shared with @creativekit/shared)
percent: number; // 0-100 — @deprecated alias of `progress`, will be removed in the next major
message: string; // Human-readable status
timeElapsed: number; // Milliseconds since start
}Progress stages and percentages:
preparing: 0%uploading: 10-80% (based on bytes uploaded)committing: 80%processing: 85-100% (based on server progress)complete: 100%
React Example
import { CreativeKitClient } from "@creativekit/client";
import { useState } from "react";
const client = new CreativeKitClient({ backendUrl: "/api/creatives" });
function UploadForm() {
const [progress, setProgress] = useState(0);
const [status, setStatus] = useState("");
const handleUpload = async (file: File) => {
try {
const result = await client.upload(file, "audio:podcast-aac", (p) => {
setProgress(p.progress);
setStatus(p.message);
});
console.log("Done!", result.id, result.status);
} catch (error) {
console.error("Upload failed:", error);
}
};
return (
<div>
<input type="file" onChange={(e) => handleUpload(e.target.files![0])} />
<progress value={progress} max={100} />
<p>{status}</p>
</div>
);
}SSE for Real-Time Updates
For monitoring creatives outside the upload flow:
import { useEffect, useRef } from "react";
function CreativeStatus({ creativeId }: { creativeId: string }) {
const [status, setStatus] = useState("PROCESSING");
useEffect(() => {
const stream = client.streamEvents(creativeId, {
onUpdate: (update) => {
setStatus(update.status);
// SSE = signal only. Fetch full details on terminal state:
if (["SUCCEEDED", "FAILED", "CANCELED"].includes(update.status)) {
client.getCreative(creativeId).then(setCreative);
}
},
});
return () => stream.close();
}, [creativeId]);
return <div>Status: {status}</div>;
}Note: SSE events contain only
id,status, andprogress. CallgetCreative()for full details (artifacts, failure info, etc.).
Finalize Workflow (Draft → Permanent)
Processed creatives start in a "draft" state. They can be previewed but will be automatically cleaned up after the draft TTL expires (default: 24 hours). To keep a creative permanently:
// After user reviews the preview and confirms
await client.finalize(creativeId);
// The creative is now permanent and won't be auto-deleted
const creative = await client.getCreative(creativeId);
console.log(creative.finalized); // true
console.log(creative.finalizedAt); // timestamp in millisecondsWhy finalize?
- Cost control: Unfinalized drafts are cleaned up automatically
- User confirmation: Let users preview before committing to storage
- Idempotent: Safe to call multiple times (no error if already finalized)
Exported Types
The SDK exports these TypeScript types for your use:
import {
// Client
CreativeKitClient,
CreativeKitClientConfig,
// Progress & Events
UploadProgress,
StreamEventsOptions,
CreativeStatusUpdate,
EventStream,
// Errors
APIError,
ErrorDetail,
// Validation (for handling failed creatives)
ValidationError,
ValidationResult,
StepResults,
// Re-exported from @creativekit/shared
Profile,
CreativeStatusResponse,
UploadResult,
// ... and more
} from "@creativekit/client";Key Types
// SSE event update (minimal signal)
interface CreativeStatusUpdate {
id: string;
status: string; // "AWAITING_UPLOAD" | "QUEUED" | "PROCESSING" | "SUCCEEDED" | "FAILED" | "CANCELED"
progress?: number; // 0.0-1.0
}
// SSE stream controller
interface EventStream {
close(): void;
readonly closed: boolean;
}
// API error structure (Google API conventions)
interface APIError {
code: number; // HTTP status code
status: string; // e.g., "FAILED_PRECONDITION"
message: string; // Human-readable message
details?: ErrorDetail[];
}
// Validation error (from results.validation.errors)
interface ValidationError {
field: string; // e.g., "aspectRatio", "duration"
rule: string; // e.g., "allowedValues", "range"
expected: string; // What the profile requires
actual: unknown; // What was found
code?: string; // e.g., "ASPECT_RATIO_NOT_ALLOWED"
message?: string; // Human-readable error
profileHint?: string; // e.g., "validate.allowedAspectRatios"
}
// Validation result container
interface ValidationResult {
passed: boolean;
errors: ValidationError[];
}Error Handling
Validation Errors (from Results)
When a creative fails validation, detailed errors are available in results.validation.errors:
const creative = await client.getCreative(id);
if (creative.status === "FAILED" && creative.results?.validation) {
console.log("Validation failed:");
for (const error of creative.results.validation.errors) {
console.log(` ${error.field}: ${error.message}`);
console.log(` Expected: ${error.expected}`);
console.log(` Actual: ${error.actual}`);
console.log(` Code: ${error.code}`);
console.log(` Profile hint: ${error.profileHint}`);
}
}Validation Error Fields:
| Field | Description |
| ----- | ----------- |
| field | Property that failed (e.g., aspectRatio, duration) |
| rule | Validation rule violated (e.g., allowedValues, range) |
| expected | What the profile requires |
| actual | What was found in the uploaded file |
| code | Machine-readable error code (e.g., ASPECT_RATIO_NOT_ALLOWED) |
| message | Human-readable error message |
| profileHint | Reference to the profile constraint |
API Errors (Exceptions)
The SDK throws ApiError for API failures (network errors, auth issues, etc.):
import { ApiError } from "@creativekit/client";
try {
const result = await client.upload(file, profile);
} catch (error) {
if (error instanceof ApiError) {
console.error("API Error:", error.message);
// Access error details
if (error.details?.code === "VALIDATION_FAILED") {
console.error("Validation failed at step:", error.details.step);
}
if (error.details?.code === "PROCESSING_FAILED") {
console.error("Processing failed:", error.details.cause);
console.error("Retriable:", error.details.retriable);
}
}
}Common error codes:
VALIDATION_FAILED- File validation failed (wrong format, size, etc.)PROCESSING_FAILED- Processing pipeline failed404- Creative not found400- Bad request (e.g., creative not ready for finalization)
Handling Both Error Types
const result = await client.upload(file, profile, onProgress);
if (result.status === "FAILED") {
// Check for validation errors (detailed)
if (result.results?.validation?.errors?.length) {
const errors = result.results.validation.errors;
console.error(`Validation failed with ${errors.length} error(s):`);
errors.forEach((e) => console.error(` - ${e.message}`));
}
// Check for pipeline errors
else if (result.failure) {
console.error(`Pipeline failed: ${result.failure.message}`);
console.error(`Retriable: ${result.failure.retriable}`);
}
}SSE Fallback to Polling
The upload() method automatically handles SSE availability:
- Tries SSE first - Connects to your backend's
/eventsendpoint - Falls back to polling - If SSE fails or doesn't connect within 2 seconds
- Polls every 2 seconds - Until processing completes
This is handled automatically - no configuration needed.
Full Documentation
See the main SDK documentation for:
- Backend setup examples (Express, Next.js, NestJS)
- Complete API reference
- AWS-style pattern explanation
- Troubleshooting guide
Security
- ✅ Never accesses CreativeKit API directly
- ✅ No credentials in browser
- ✅ Only talks to YOUR backend
- ✅ You control access with your auth
License
MIT
