User menu
    • SnapiX About
    • SnapiX API Reference
    • SnapiX MCP Reference
    • SnapiX SDK Reference
    • SnapiX Plans
AU
By using this site you accept the terms of use, privacy policy and cookie policy.
App logo

SnapiX SDK

@metalevel/snapix-sdk-core is a typed Type­Script SDK that lets you in­te­grate SnapiX into your ap­pli­ca­tions - im­age up­load, con­ver­sion, re­siz­ing, gallery man­age­ment, and AI gen­er­a­tion - with full type safe­ty and zero run­time de­pen­den­cies. Three client class­es cov­er every run­time: a full-fea­tured Node.js serv­er client, a brows­er-safe client for any JS run­time, and an ab­stract base you can ex­tend di­rect­ly.

  • Full Type­Script types for all re­quests and re­spons­es
  • Zero run­time de­pen­den­cies - uses na­tive fetch and FormData
  • Three client class­es - SnapixClientServer (Node.js, full CRUD), SnapixClientBrowser (any JS run­time, read + con­vert), SnapixClientBasic (ab­stract base)
  • Auto-con­fig­u­ra­tion from en­vi­ron­ment vari­ables

Contents

  • In­stal­la­tion
    • Au­to­mat­ed Set­up via MCP
  • Quick Start
    • Snapix­ClientServ­er
    • Snapix­Client­Brows­er
  • Class Hi­er­ar­chy
  • Pack­age Ex­ports
    • Why three en­try points?
    • Sub­path ex­ports
  • Snapix­Client­Ba­sic
    • Con­fig­u­ra­tion
    • Log­ging
    • Read Meth­ods
    • Er­ror Han­dling
  • Snapix­Client­Brows­er
    • En­vi­ron­ment Vari­ables
    • Man­u­al Con­fig­u­ra­tion
    • Read Meth­ods
    • Con­vert Meth­ods
  • Snapix­ClientServ­er
    • En­vi­ron­ment Vari­ables
    • Man­u­al Con­fig­u­ra­tion
    • Read Meth­ods
    • Im­age Meth­ods
    • Con­vert Meth­ods
    • Gen­er­ate Method (AI)
    • Gallery Meth­ods
    • Next.js In­te­gra­tion
  • Con­stants Ref­er­ence
  • Type­Script Types Ref­er­ence
  • SDK Pre­view
  • See Also

In­stal­la­tion

npm install @metalevel/snapix-sdk-core

or

pnpm add @metalevel/snapix-sdk-core

Au­to­mat­ed Set­up via MCP

If you have the SnapiX MCP serv­er con­fig­ured in your AI client, you can in­stall and con­fig­ure Snapix SDK Core au­to­mat­i­cal­ly us­ing the built-in snapix_setup_sdk_core prompt - no man­u­al steps re­quired.

In VS Code Copi­lot, type / in chat and se­lect snapix_set­up_sdk_core. The agent will read the live SDK doc­u­men­ta­tion, in­stall @metalevel/snapix-sdk-core us­ing your pro­jec­t's pack­age man­ag­er, and ap­pend the re­quired SNAPIX_* en­vi­ron­ment vari­ables to your .env file.

See the MCP set­up guide to con­fig­ure the MCP serv­er if you haven't al­ready.

Quick Start

Snapix­ClientServ­er

Up­load an im­age from your Node.js serv­er us­ing SNAPIX_API_KEY (get one at API Keys):

export SNAPIX_API_KEY="sk_snapix_apiKey-a1b2c3-placeholder"
import { SnapixClientServer } from "@metalevel/snapix-sdk-core";

// Auto-loads config from environment variables
const client = new SnapixClientServer();

const result = await client.uploadImage({
  imageUrl: "https://example.com/photo.jpg",
  name: "my-photo",
  formatOptions: [{ format: "webp" }],
});

console.log(result.simpleData.variants);
// { webp: "https://cdn.example.com/my-photo.webp" }

Snapix­Client­Brows­er

Read im­ages and gal­leries safe­ly in any JS run­time us­ing NEXT_PUBLIC_SNAPIX_API_KEY. A read-only API key is suf­fi­cient and rec­om­mend­ed:

export NEXT_PUBLIC_SNAPIX_API_KEY="sk_snapix_apiKey-a1b2c3-placeholder"
import { SnapixClientBrowser } from "@metalevel/snapix-sdk-core/browser";

// Auto-loads config from NEXT_PUBLIC_SNAPIX_* environment variables
const client = new SnapixClientBrowser();

// List galleries
const { galleries } = await client.listGalleries();

// List images with pagination
const { data: images, simpleData } = await client.listImages({ page: 1, limit: 10 });

// Get a single image
const { data: image } = await client.getImage({ imageId: "image-uuid" });
console.log(image.urlBase, image.metadata);

Class Hi­er­ar­chy

SnapixClientBasic           (abstract - shared read methods, zero Node.js deps)
├── SnapixClientServer      (full CRUD + Node.js file I/O, uses SNAPIX_* env vars)
└── SnapixClientBrowser     (read + convert, browser-safe, uses NEXT_PUBLIC_SNAPIX_* env vars)

SnapixClientBasic is the ab­stract base - you do not in­stan­ti­ate it di­rect­ly. Use SnapixClientServer in Node.js en­vi­ron­ments for full ac­cess to up­load, gen­er­ate, and gallery write op­er­a­tions. Use SnapixClientBrowser in browsers, edge run­times, or any en­vi­ron­ment where you only need read ac­cess and on-the-fly im­age con­ver­sion with a re­strict­ed API key.

Pack­age Ex­ports

The SDK ships three ded­i­cat­ed en­try points. Use the sub­path that match­es your run­time - im­port­ing from the wrong one will cause build er­rors in brows­er-tar­get­ing bundlers (Tur­bopack, Web­pack, Vite, etc.).

Why three en­try points?

SnapixClientServer uses node:fs/promises for file I/O. Brows­er bundlers sta­t­i­cal­ly re­solve every im­port in a mod­ule's graph, even code you nev­er call at run­time. When a bar­rel file re-ex­ports both SnapixClientServer and SnapixClientBrowser to­geth­er, the bundler tries to in­clude node:fs/promises in the brows­er chunk - and fails with an er­ror like:

the chunking context does not support external modules (request: node:fs/promises)

The so­lu­tion is to pro­vide sub­path ex­ports so that each en­try point only pulls in what its tar­get run­time sup­ports.

Sub­path ex­ports

Im­port path Class Use in
@metalevel/snapix-sdk-core SnapixClientServer Node.js serv­er, MCP serv­er, Next.js serv­er ac­tions, API routes
@metalevel/snapix-sdk-core/browser SnapixClientBrowser Brows­er, Next.js client com­po­nents, edge run­times
@metalevel/snapix-sdk-core/basic SnapixClientBasic Cus­tom sub­class­es only
@metalevel/snapix-sdk-core/server SnapixClientServer Alias for root - iden­ti­cal to "."

All sub­paths also ex­port the er­ror class­es (SnapixApiError, SnapixConfigError) and all Type­Script types rel­e­vant to that client.

Snapix­Client­Ba­sic

The ab­stract base class shared by both sub­class­es. It holds all read meth­ods and re­quires zero Node.js de­pen­den­cies. Use it only if you are ex­tend­ing the SDK with a cus­tom sub­class; oth­er­wise use SnapixClientServer or SnapixClientBrowser di­rect­ly.

Con­fig­u­ra­tion

Pass op­tions di­rect­ly to the con­struc­tor:

// When subclassing SnapixClientBasic directly:
super({
  apiKey: "your_api_key",
  baseUrl: "https://www.snapix.space", // optional
  bucketKey: "my-bucket",              // optional
  logLevel: "debug",                   // optional
});

Log­ging

The logLevel op­tion (or the cor­re­spond­ing env var on each sub­class) con­trols log ver­bosi­ty:

Lev­el De­scrip­tion
debug All re­quests logged with method + URL
info In­for­ma­tion­al mes­sages (e.g., file writ­ten)
warn Rate lim­it hits (HTTP 429)
error API er­rors, quo­ta ex­ceed­ed
silent No out­put

Read Meth­ods

All read meth­ods are in­her­it­ed by both SnapixClientServer and SnapixClientBrowser:

// List images with optional pagination and filters
await client.listImages(params?: ListImagesParams): Promise<ListImagesResponse>
// params: { page?, limit?, sort?: "asc" | "desc", bucketKey? }
// response includes: data, simpleData, accountStatistics, pagination

// Get a single image by ID
await client.getImage(params: GetImageParams): Promise<GetImageResponse>
// params: { imageId }

// List all galleries
await client.listGalleries(): Promise<ListGalleriesResponse>

// Get a single gallery with its images
await client.getGallery(params: GetGalleryParams): Promise<GetGalleryResponse>
// params: { galleryId }

// Get images not assigned to any gallery
await client.getImagesWithoutGallery(params?: GetImagesWithoutGalleryParams): Promise<GetGalleryResponse>
// params: { bucketKey? }

// Fetch a documentation page as Markdown
await client.getDocs(params: GetDocsParams): Promise<string>
// params: { docType: "sdk" | "api" | "mcp" | "about" }

Er­ror Han­dling

Both SnapixApiError and SnapixConfigError are thrown by all three client class­es. Im­port them from the same sub­path as your client:

// Server / Node.js
import { SnapixClientServer, SnapixApiError, SnapixConfigError } from "@metalevel/snapix-sdk-core";

// Browser / client components
// import { SnapixClientBrowser, SnapixApiError, SnapixConfigError } from "@metalevel/snapix-sdk-core/browser";

try {
  const client = new SnapixClientServer(); // throws SnapixConfigError if SNAPIX_API_KEY is missing
  const result = await client.uploadImage({ imageUrl: "https://..." });
} catch (err) {
  if (err instanceof SnapixConfigError) {
    // Missing API key or invalid configuration
    console.error("Configuration error:", err.message);
    // e.g. "SNAPIX_API_KEY environment variable is required but not set."
  } else if (err instanceof SnapixApiError) {
    console.error("API error:", err.message, "status:", err.status);
    if (err.isRetryable) {
      // HTTP 429 - rate limit hit, retry after backoff
    }
    if (err.status === 402) {
      // Quota exceeded - check your plan
    }
    if (err.isReadOnly) {
      // HTTP 403 - key lacks required permission for this operation; check key permissions
    }
  }
}

Snapix­Client­Brows­er

De­signed for any JavaScript run­time - browsers, Next.js client com­po­nents, edge run­times. Zero Node.js de­pen­den­cies. Reads NEXT_PUBLIC_SNAPIX_* en­vi­ron­ment vari­ables by de­fault (stan­dard in Next.js), but ac­cepts ex­plic­it con­fig op­tions in any en­vi­ron­ment.

Se­cu­ri­ty: When used client-side, your API key is ex­posed in the brows­er bun­dle. Use a ded­i­cat­ed API key with re­strict­ed read-only per­mis­sions - see API Key Per­mis­sions.

En­vi­ron­ment Vari­ables

Vari­able Re­quired De­fault De­scrip­tion
NEXT_PUBLIC_SNAPIX_API_KEY Yes - Your SnapiX API key
NEXT_PUBLIC_SNAPIX_BASE_URL No https://www.snapix.space Over­ride API base URL
NEXT_PUBLIC_SNAPIX_BUCKET_KEY No pri­ma­ry buck­et De­fault stor­age buck­et key
NEXT_PUBLIC_SNAPIX_LOG_LEVEL No warn debug | info | warn | error | silent

Man­u­al Con­fig­u­ra­tion

import { SnapixClientBrowser } from "@metalevel/snapix-sdk-core/browser";

const client = new SnapixClientBrowser({
  apiKey: "your_api_key",
  baseUrl: "https://www.snapix.space", // optional
  bucketKey: "my-bucket",              // optional
  logLevel: "debug",                   // optional
});

Read Meth­ods

SnapixClientBrowser in­her­its all read meth­ods from SnapixClientBasic - see Read Meth­ods above.

Con­vert Meth­ods

On-the-fly con­ver­sion - re­sults are not stored in cloud stor­age. imageFilePath is not sup­port­ed (no filesys­tem ac­cess in brows­er en­vi­ron­ments); use SnapixClientServer for that. imageBlob ac­cepts a File from <input type="file"> di­rect­ly - no base64 en­cod­ing need­ed.

Write meth­ods (uploadImage, updateImage, deleteImage, generateImage, and all gallery write meth­ods) are only avail­able on SnapixClientServer.

convertImage - raw bi­na­ry + MIME type

await client.convertImage(params: ConvertImageParams): Promise<ConvertImageBrowserResult>
// ConvertImageBrowserResult: { buffer: Uint8Array, type: string }
// `type` is the MIME type from the API response Content-Type header
const file = inputElement.files[0];
const result = await client.convertImage({
  imageBlob: file,
  formatOptions: { format: "webp" },
  resizeOptions: { width: 800 },
});
// result.buffer - Uint8Array of the converted image
// result.type  - e.g. "image/webp"

convertImageToBlob - re­turns a Blob

await client.convertImageToBlob(params: ConvertImageToBlobParams): Promise<Blob>
// params extends ConvertImageParams with { mimeType?: string }
// mimeType overrides the API-returned Content-Type; defaults to result.type
const blob = await client.convertImageToBlob({
  imageBlob: file,
  formatOptions: { format: "webp" },
});

convertImageToObjectUrl - re­turns a blob: URL

await client.convertImageToObjectUrl(params: ConvertImageToObjectUrlParams): Promise<string>
// params extends ConvertImageParams with { mimeType?: string }
// Returns a temporary blob: URL - caller must call URL.revokeObjectURL() when done
const objectUrl = await client.convertImageToObjectUrl({
  imageBlob: file,
  formatOptions: { format: "webp" },
});
imgElement.src = objectUrl;
// Later, when no longer needed:
URL.revokeObjectURL(objectUrl);

convertImageAndDownload - trig­gers a down­load di­a­log

await client.convertImageAndDownload(params: ConvertImageAndDownloadParams): Promise<void>
// params extends ConvertImageParams with { filename: string, mimeType?: string }
// Browser-only - throws if called outside a browser environment (SSR, Node.js, Workers)
// URL.revokeObjectURL() is called automatically after the download is triggered
await client.convertImageAndDownload({
  imageBlob: file,
  formatOptions: { format: "avif" },
  filename: "converted.avif",
});

Snapix­ClientServ­er

The full-fea­tured serv­er client for Node.js ≥ 18. Pro­vides all read meth­ods in­her­it­ed from SnapixClientBasic, plus im­age up­load, up­date, delete, AI gen­er­a­tion, on-the-fly con­ver­sion to Buffer, and gallery man­age­ment.

En­vi­ron­ment Vari­ables

Vari­able Re­quired De­fault De­scrip­tion
SNAPIX_API_KEY Yes - Your SnapiX API key
SNAPIX_BASE_URL No https://www.snapix.space Over­ride API base URL
SNAPIX_BUCKET_KEY No pri­ma­ry buck­et De­fault stor­age buck­et key
SNAPIX_LOG_LEVEL No warn Log ver­bosi­ty (see Log­ging)

Man­u­al Con­fig­u­ra­tion

import { SnapixClientServer } from "@metalevel/snapix-sdk-core";

const client = new SnapixClientServer({
  apiKey: "your_api_key",
  baseUrl: "https://www.snapix.space", // optional
  bucketKey: "my-bucket",              // optional
  logLevel: "debug",                   // optional
});

Read Meth­ods

SnapixClientServer in­her­its all read meth­ods from SnapixClientBasic - see Read Meth­ods above.

Im­age Meth­ods

// Upload from URL, file path, base64, or Blob/File
await client.uploadImage(params: UploadImageParams): Promise<UploadImageResponse>

// Update metadata and/or replace image content
await client.updateImage(params: UpdateImageParams): Promise<UpdateImageResponse>
// params: { imageId, name?, description?, galleries?, formatOptions?, resizeOptions?, imageUrl?, ... }

// Delete an image
await client.deleteImage(params: DeleteImageParams): Promise<{ success: true }>
// params: { imageId }

Up­load ex­am­ple - for­mat + re­size com­bi­na­tions, as­sign to gallery:

const result = await client.uploadImage({
  imageUrl: "https://example.com/photo.jpg",
  name: "my-photo",
  description: "A landscape photo",
  formatOptions: [{ format: "webp" }, { format: "avif" }],
  resizeOptions: [{ width: 1280 }, { width: 640 }],
  galleries: ["gallery-uuid"],
});
// Costs 4 credits (2 formats × 2 resizes)
console.log(result.simpleData); // [{ id, originalName, variants, info }, ...]

Up­date ex­am­ple - meta­da­ta only, or re­place the im­age file:

// Metadata-only update
await client.updateImage({
  imageId: "image-uuid",
  name: "new-name",
  description: "Updated description",
  galleries: ["gallery-uuid"],
});

// Replace image content
await client.updateImage({
  imageId: "image-uuid",
  imageFilePath: "/tmp/new-version.png",
  formatOptions: [{ format: "webp" }],
});

Con­vert Meth­ods

On-the-fly con­ver­sion - re­sults are not stored in cloud stor­age. Ac­cepts imageFilePath, imageBlob, imageBase64, or imageUrl. Costs 1 cred­it per call.

// Returns binary data as a Buffer
await client.convertImage(params: ConvertImageParams): Promise<Buffer>

// Converts and writes directly to disk
await client.convertImageToFile(params: ConvertImageToFileParams): Promise<void>
// params extends ConvertImageParams with { outputPath: string }
// From URL
const buffer = await client.convertImage({
  imageUrl: "https://example.com/photo.jpg",
  formatOptions: { format: "webp" },
  resizeOptions: { width: 400 },
});

// From file path
const buffer = await client.convertImage({
  imageFilePath: "/tmp/source.png",
  formatOptions: { format: "avif" },
});

// Write directly to disk
await client.convertImageToFile({
  imageFilePath: "/tmp/source.png",
  formatOptions: { format: "avif" },
  outputPath: "/tmp/output.avif",
});

Gen­er­ate Method (AI)

Gen­er­ate an im­age from a text prompt us­ing AI. Re­quires a paid sub­scrip­tion.

await client.generateImage(params: GenerateImageParams): Promise<GenerateImageResponse>
// From text prompt only
const result = await client.generateImage({
  promptText: "A serene mountain lake at sunset",
  name: "mountain-lake",
  formatOptions: [{ format: "webp" }],
});
// Costs 40+ credits

// From text prompt + image template (image-to-image)
const result = await client.generateImage({
  promptText: "Transform into an oil painting style",
  imageUrl: "https://example.com/source-photo.jpg",
  name: "oil-painting",
  formatOptions: [{ format: "webp" }],
});
// Also accepts imageFilePath, imageBase64, or imageBlob as the template source

Gallery Meth­ods

// Create a gallery (server-only)
await client.createGallery(params: CreateGalleryParams): Promise<CreateGalleryResponse>

// Update gallery name or visibility (server-only)
await client.updateGallery(params: UpdateGalleryParams): Promise<GalleryType>
// params: { galleryId, name?, isPublic? }

// Delete a gallery; pass deleteImages: true to also delete all its images (server-only)
await client.deleteGallery(params: DeleteGalleryParams): Promise<{ success: boolean }>
// params: { galleryId, deleteImages? }

// Inherited read methods from SnapixClientBasic:
await client.listGalleries(): Promise<ListGalleriesResponse>
await client.getGallery(params: GetGalleryParams): Promise<GetGalleryResponse>
await client.getImagesWithoutGallery(params?: GetImagesWithoutGalleryParams): Promise<GetGalleryResponse>
// Create
const { gallery } = await client.createGallery({ name: "My Portfolio", isPublic: true });

// Update
await client.updateGallery({ galleryId: gallery.id, isPublic: false });

// Delete gallery only (keep images)
await client.deleteGallery({ galleryId: gallery.id });

// Delete gallery and all its images
await client.deleteGallery({ galleryId: gallery.id, deleteImages: true });

Next.js In­te­gra­tion

Use SnapixClientServer in serv­er ac­tions or API routes - nev­er in client com­po­nents. Client com­po­nents must use SnapixClientBrowser im­port­ed from @metalevel/snapix-sdk-core/browser:

// app/actions/upload.ts  - server action
"use server";
import { SnapixClientServer } from "@metalevel/snapix-sdk-core";

const client = new SnapixClientServer(); // reads SNAPIX_API_KEY from env

export async function uploadProfileImage(formData: FormData) {
  const file = formData.get("image") as File;
  const base64 = Buffer.from(await file.arrayBuffer()).toString("base64");

  const result = await client.uploadImage({
    imageBase64: base64,
    imageContentType: file.type,
    name: "profile-image",
    formatOptions: [{ format: "webp" }],
    resizeOptions: [{ width: 256, height: 256 }],
  });

  return result.simpleData[0].variants["webp"];
}
// components/gallery.tsx  - client component
"use client";
import { SnapixClientBrowser } from "@metalevel/snapix-sdk-core/browser";

// Instantiate once outside the component to avoid re-creating on every render.
// NEXT_PUBLIC_SNAPIX_API_KEY must be a read-only key - it will be visible in the browser bundle.
const client = new SnapixClientBrowser();

export function Gallery() {
  // ...
  const { galleries } = await client.listGalleries();
  // ...
}

Con­stants Ref­er­ence

Some run­time con­stants are ex­port­ed from every sub­path along­side types. Im­port them from the same en­try point as your client:

export {
  NEXT_PUBLIC_SNAPIX_BASE_URL as nextPublicSnapixBaseUrl,
  SNAPIX_BASE_URL as snapixBaseUrl,
  APP_SERVER_GALLERY_URI as snapixGalleryUri,
} from "./constants.js";

SNAPIX_BASE_URL and NEXT_PUBLIC_SNAPIX_BASE_URL are par­tic­u­lar­ly use­ful when con­struct­ing im­age URLs or links to the SnapiX app with­out hard-cod­ing the do­main:

import { snapixBaseUrl, snapixGalleryUri } from "@metalevel/snapix-sdk-core";

const galleryPageUrl = `${snapixBaseUrl}${snapixGalleryUri}/${galleryId}`;

Type­Script Types Ref­er­ence

All types are ex­port­ed from every sub­path. Im­port them from the same en­try point as your client to avoid mix­ing serv­er and brows­er mod­ule graphs:

// Server / Node.js - import from root
import type {
  UploadImageParams,
  UpdateImageParams,
  DeleteImageParams,
  ConvertImageToFileParams,
  GenerateImageParams,
  CreateGalleryParams,
  UpdateGalleryParams,
  DeleteGalleryParams,
  ImageSourceParams,
  UploadImageResponse,
  UpdateImageResponse,
  GenerateImageResponse,
  // ... plus all shared types below
} from "@metalevel/snapix-sdk-core";

// Browser / client components - import from /browser
import type {
  ConvertImageParams,
  ConvertImageBrowserResult,
  ConvertImageToBlobParams,
  ConvertImageToObjectUrlParams,
  ConvertImageAndDownloadParams,
  // ... plus all shared types below
} from "@metalevel/snapix-sdk-core/browser";

// Shared types - available from all subpaths
import type {
  // Request params (read)
  ListImagesParams,
  GetImageParams,
  GetGalleryParams,
  GetImagesWithoutGalleryParams,
  GetDocsParams,

  // Response types
  ListImagesResponse,
  GetImageResponse,
  GetGalleryResponse,
  ListGalleriesResponse,
  CreateGalleryResponse,

  // Entity types
  ImageType,
  ImageMetadata,
  ImageInfo,
  ImageGalleryRef,
  ImageDataSimplified,
  GalleryType,
  GalleryWithImagesType,
  GalleryImageEntry,
  AccountStatistics,
  Pagination,
  StorageUsed,

  // Config
  GetDocsDocType,
  SnapixClientOptions,
  LogLevel,
} from "@metalevel/snapix-sdk-core"; // or /browser or /basic

SDK Pre­view

The snapix-sdk-pre­view repos­i­to­ry con­tains a pri­vate Next.js + shad­cn/ui ap­pli­ca­tion used to in­ter­ac­tive­ly test and pre­view SDK pack­ages against the live SnapiX API. It cov­ers @metalevel/snapix-sdk-core and will be ex­tend­ed as new SDK vari­ants (e.g. sdk-react) are in­tro­duced.

See Also

  • REST API Ref­er­ence - di­rect HTTP API doc­u­men­ta­tion
  • MCP Serv­er - use SnapiX with AI as­sis­tants (Claude, VS Code Copi­lot)
  • SDK Pre­view App - in­ter­ac­tive Next.js test app for the SDK
  • API Keys - man­age your API keys
  • API Key Per­mis­sions - gran­u­lar per­mis­sions ref­er­ence
Powered by