Suparse

JS / TS SDK & CLI

Last updated: 2026-05-15

Suparse JavaScript SDK and CLI

Official JavaScript/TypeScript SDK and CLI for the Suparse Document Processing API.

Suparse is an AI-powered document processing API for extracting structured data from any document type, including invoices, receipts, bank statements, purchase orders and many more. This repository contains:

  • @suparse/sdk: TypeScript SDK for browser, edge, and Node.js runtimes
  • suparse: command-line interface for processing documents from your terminal

Requirements

  • Node.js 20+
  • Package manager: npm, pnpm, yarn, or bun

Installation

Install the SDK:

npm install @suparse/sdk

Install the CLI globally:

npm install -g suparse

Or run the CLI without a global install:

npx suparse process invoice.pdf -o results.json

Authentication

You'll need an API key to use the SDK or CLI. To obtain one:

  1. Sign in at suparse.com
  2. Go to the API Keys tab
  3. Enter a key name and click Generate New Key
  4. Copy the key value. It will be shown only once.

Set it as an environment variable:

export SUPARSE_API_KEY="your_api_key_here"

Or pass it directly to the SDK constructor:

import { SuparseNodeClient } from "@suparse/sdk/node";
 
const client = new SuparseNodeClient({ apiKey: "your_api_key_here" });

Quick Start

# CLI
suparse process invoice.pdf -o results.json
// Node.js SDK, with SUPARSE_API_KEY set
import { SuparseNodeClient } from "@suparse/sdk/node";
 
const client = new SuparseNodeClient();
 
try {
  const result = await client.extract("invoice.pdf");
 
  for (const item of result.succeeded) {
    console.log(item.original_file);
    console.log(item.documents.map((doc) => doc.extracted_data));
  }
} finally {
  await client.close();
}
// Browser or edge runtime
import { SuparseClient } from "@suparse/sdk";
 
const client = new SuparseClient({ apiKey: "your_api_key_here" });
const file = new File([fileBytes], "invoice.pdf", { type: "application/pdf" });
 
const result = await client.extract(file);
console.log(result.succeeded);

CLI Usage

Run suparse --help or suparse process --help for full usage information.

Set your API key and process a file directly from the terminal. The CLI will auto-upload, poll, and download the resulting JSON.

Process a Document

export SUPARSE_API_KEY="your_api_key_here"
 
# Auto-detect template
suparse process path/to/invoice.pdf -o results.json
 
# Use a specific template without auto-splitting
suparse process path/to/invoice.pdf --template-id 276a0aa8-84bc-4491-a2e7-1ea13381790c
 
# Auto-split a multi-page PDF containing mixed document types
suparse process path/to/merged.pdf --with-split
 
# Use a specific template with auto-splitting
suparse process path/to/invoice.pdf --template-id 276a0aa8-84bc-4491-a2e7-1ea13381790c --with-split
 
# Process and auto-delete documents from the server after download
suparse process path/to/invoice.pdf --cleanup

Process a Folder

Process all supported files (.pdf, .jpg, .jpeg, .png, .heic, .heif) in a folder. Files are uploaded and polled individually, then results are exported to a single JSON file.

# Process all supported files in a folder
suparse process --folder path/to/receipts/
 
# Output to a specific file (default: {folder_name}_results.json)
suparse process --folder path/to/receipts/ -o all_results.json
 
# Process a folder with a specific template
suparse process --folder path/to/receipts/ --template-id 276a0aa8-84bc-4491-a2e7-1ea13381790c
 
# Process a folder with auto-splitting enabled
suparse process --folder path/to/receipts/ --with-split
 
# Process a folder and auto-delete documents from the server after download
suparse process --folder path/to/receipts/ --cleanup

Delete Documents

# Delete one or more documents by ID (prompts for confirmation)
suparse delete <document_id>
suparse delete <id1> <id2> <id3>
 
# Skip confirmation prompt
suparse delete <id1> <id2> -y

Deleting a parent document automatically deletes all its child documents server-side.

List Available Templates

Templates define how a document type (invoice, receipt, bank statement, etc.) is parsed. Before processing a document, check which templates are already assigned to your account:

# List templates assigned to your account (table format)
suparse templates
 
# List templates in JSON format
suparse templates --format json
 
# Include all system templates
suparse templates --include-system

The recommended way to process documents is with auto-split enabled (--with-split), which handles both single-type and mixed document types automatically:

suparse process path/to/documents.pdf --with-split -o results.json

If you consistently process one document type, look up the template ID and pass it directly:

  1. Run suparse templates to see templates assigned to your account.

  2. Use the matching template ID:

    suparse process invoice.pdf --template-id <id> -o results.json
  3. If no template matches, run suparse templates --include-system to browse all system templates. Assign one to your account via the Suparse UI.

  4. If no system template fits, create a custom template using the template creator in the Suparse UI.

Configuration

The CLI reads settings from environment variables and global flags.

VariableDefaultDescription
SUPARSE_API_URLhttps://api.suparse.com/api/v1API base URL
SUPARSE_API_KEY-Your API key (required)

Priority: CLI flags > environment variables > defaults.

Global Options

These options apply to all subcommands.

OptionDescription
--api-urlAPI URL (default: from SUPARSE_API_URL env var)
--api-keyAPI key (default: from SUPARSE_API_KEY env var)
-v, --verboseEnable verbose output

CLI Options

CommandOptionDescription
process--folderProcess all supported files in a folder
process-o, --outputOutput JSON file path (default: {file_stem}_results.json, folder mode: {folder_name}_results.json)
process--template-idTemplate ID to use (default: auto-detect)
process--with-splitAuto-split multi-page documents containing mixed document types
process--cleanupDelete documents from server after download
templates--formatOutput format: table or json (default: table)
templates--include-systemInclude system templates
delete-y, --yesSkip confirmation prompt

SDK Usage

The SDK exports two clients:

  • SuparseClient from @suparse/sdk: browser/edge-compatible client for Blob, File, and URL inputs
  • SuparseNodeClient from @suparse/sdk/node: Node.js client with file paths, folder processing, and disk output helpers

Both clients handle uploads, polling, exports, retries, rate limits, and parallel batch processing. Batch extraction runs up to 10 files concurrently.

Node.js

Use @suparse/sdk/node for local files and server-side applications.

import { SuparseNodeClient } from "@suparse/sdk/node";
 
const client = new SuparseNodeClient();
 
try {
  const result = await client.extract(["invoice1.pdf", "invoice2.pdf"]);
 
  for (const item of result.succeeded) {
    console.log(item.original_file);
    console.log(item.documents.map((doc) => doc.extracted_data));
  }
 
  for (const failed of result.failed) {
    console.error(failed.file, failed.error);
  }
} finally {
  await client.close();
}

The Node client reads SUPARSE_API_KEY and SUPARSE_API_URL from environment variables by default, so you can use new SuparseNodeClient() if those are set. Pass apiKey and baseUrl directly when you do not want to use environment variables.

Browser and Edge

Use @suparse/sdk for runtimes without Node.js file-system APIs.

import { SuparseClient } from "@suparse/sdk";
 
const client = new SuparseClient({ apiKey: "your_api_key_here" });
 
const result = await client.extract(fileInput.files![0], {
  split: true,
});
 
for (const item of result.succeeded) {
  console.log(item.documents.map((doc) => doc.extracted_data));
}

You can also pass a URL; the SDK fetches it and uploads the response body:

const result = await client.extract(new URL("https://example.com/invoice.pdf"));

Extract One or More Documents

extract() is the primary SDK API.

Node.js File Paths

import { SuparseNodeClient } from "@suparse/sdk/node";
 
const client = new SuparseNodeClient();
 
const result = await client.extract("invoice.pdf", {
  template_id: "276a0aa8-84bc-4491-a2e7-1ea13381790c",
  split: true,
  cleanup: true,
  onProgress: (item) => {
    if ("file" in item) {
      console.error(`Failed: ${item.file} - ${item.error}`);
    } else {
      console.log(`Done: ${item.original_file}`);
    }
  },
});

SuparseNodeClient accepts a single file path, an array of file paths, Blob/File objects, URL objects, or an array mixing those input types.

Batch Processing

const result = await client.extract(["receipts/jan.pdf", "receipts/feb.pdf"]);
 
for (const item of result.succeeded) {
  console.log(item.original_file, item.documents);
}
 
for (const failed of result.failed) {
  console.error(failed.file, failed.error);
}
 
console.log(`Total: ${result.total}`);

Browser Files

import { SuparseClient } from "@suparse/sdk";
 
const client = new SuparseClient({ apiKey: "your_api_key_here" });
const files = Array.from(fileInput.files ?? []);
 
const result = await client.extract(files, {
  split: false,
  auto_approve: true,
});

SuparseClient accepts Blob, File, and URL inputs. Use SuparseNodeClient when you need local file paths or disk output helpers.

Extract a Folder

extractFolder() is available from SuparseNodeClient. It scans a directory for supported files and delegates to extract().

import { SuparseNodeClient } from "@suparse/sdk/node";
 
const client = new SuparseNodeClient();
 
const result = await client.extractFolder("./receipts/", {
  template_id: "276a0aa8-84bc-4491-a2e7-1ea13381790c",
  split: true,
  cleanup: true,
});
 
for (const item of result.succeeded) {
  console.log(item.original_file, item.documents);
}

extractFolder() scans the immediate directory only, filters to supported extensions, sorts the files by name, and returns an empty BatchResult when no supported files are found.

Result Data

Each successful item is a TaskExport. Its documents array contains the extracted document records and parsed fields:

for (const item of result.succeeded) {
  console.log(item.task_id);
  console.log(item.original_file);
 
  for (const document of item.documents) {
    console.log(document.document_id);
    console.log(document.template_id);
    console.log(document.page_start, document.page_end);
    console.log(document.credits_used);
    console.log(document.extracted_data);
  }
}

For single-page documents, documents usually has one entry. When split is enabled, a single uploaded PDF can produce multiple document entries with their own page ranges and template IDs.

Low-Level API

Use the low-level methods when you need direct control over upload, polling, export, and deletion.

import { SuparseNodeClient } from "@suparse/sdk/node";
 
const client = new SuparseNodeClient();
 
// Upload a file and get back a task ID
const taskId = await client.uploadFile("invoice.pdf", {
  template_id: "276a0aa8-84bc-4491-a2e7-1ea13381790c",
  split: false,
  auto_approve: true,
});
 
// Poll until processing completes
const { status, documentIds } = await client.pollTaskStatus(taskId);
 
// Fetch results in memory
const exportsJson = await client.fetchResults(documentIds);
 
// Or write results to disk
await client.downloadResults(documentIds, "output.json");
 
// Delete documents by ID
await client.deleteDocuments(["550e8400-e29b-41d4-a716-446655440000"]);
 
// List available templates
const templates = await client.listTemplates();
for (const template of templates) {
  console.log(`${template.name} (${template.template_language})`);
}
 
// Include system templates too
const allTemplates = await client.listTemplates({ includeSystem: true });

Browser and edge runtimes can use uploadFromSource() instead of uploadFile():

import { SuparseClient } from "@suparse/sdk";
 
const client = new SuparseClient({ apiKey: "your_api_key_here" });
 
const taskId = await client.uploadFromSource(fileInput.files![0], {
  split: true,
  auto_approve: true,
});
const { documentIds } = await client.pollTaskStatus(taskId);
const exportsJson = await client.fetchResults(documentIds);

Node Convenience Methods

SuparseNodeClient also exposes convenience methods for file-based workflows:

import { SuparseNodeClient } from "@suparse/sdk/node";
 
const client = new SuparseNodeClient();
 
// Process one document and write the JSON export to disk.
await client.processDocument("invoice.pdf", "results.json", {
  template_id: "276a0aa8-84bc-4491-a2e7-1ea13381790c",
  split: false,
  cleanup: true,
});
 
// Process multiple files and receive raw task/document IDs.
const { succeeded, failed } = await client.processBatch(["a.pdf", "b.pdf"], {
  template_id: "276a0aa8-84bc-4491-a2e7-1ea13381790c",
  split: true,
});
 
for (const item of succeeded) {
  console.log(item.filePath, item.taskId, item.documentIds);
}
 
for (const item of failed) {
  console.error(item.filePath, item.taskId, item.error);
}

Error Handling

All SDK exceptions inherit from SuparseError.

import {
  SuparseNodeClient,
  SuparseError,
  SuparseAuthError,
  SuparseNetworkError,
  SuparsePollingTimeoutError,
} from "@suparse/sdk/node";
 
const client = new SuparseNodeClient({ apiKey: "your_api_key_here" });
 
try {
  const result = await client.extract("invoice.pdf");
  console.log(result.succeeded);
} catch (error) {
  if (error instanceof SuparseAuthError) {
    console.error("Invalid API key");
  } else if (error instanceof SuparseNetworkError) {
    console.error("Connection failed");
  } else if (error instanceof SuparsePollingTimeoutError) {
    console.error("Processing timed out");
  } else if (error instanceof SuparseError) {
    console.error(`Unexpected Suparse error: ${error.message}`);
  } else {
    throw error;
  }
}

For batch operations, check result.failed to handle per-file errors without catching exceptions:

const result = await client.extract(["a.pdf", "b.pdf", "c.pdf"]);
 
for (const item of result.succeeded) {
  console.log(`OK: ${item.original_file} -> ${item.documents.map((doc) => doc.document_id)}`);
}
 
for (const failed of result.failed) {
  console.error(`FAIL: ${failed.file} -> ${failed.error}`);
}

Reference

Constructor Parameters

SuparseClient requires apiKey directly. SuparseNodeClient can read apiKey and baseUrl from environment variables.

ParameterTypeDefaultDescription
apiKeystringSUPARSE_API_KEY in SuparseNodeClient onlyYour API key
baseUrlstringSUPARSE_API_URL env var or https://api.suparse.com/api/v1API base URL
timeoutMsnumber60000Request timeout in milliseconds
maxRetriesnumber3Max retry attempts for retryable network/API errors
pollIntervalnumber5Initial seconds between polling attempts
maxPollAttemptsnumber300Max polling attempts before timeout

Polling uses exponential backoff starting from pollInterval seconds and caps the delay at 15 seconds. maxPollAttempts limits the total number of poll attempts before SuparsePollingTimeoutError is thrown.

Result Objects

ObjectPropertiesDescription
TaskExporttask_id, original_file, total_documents_extracted, documentsSuccessfully extracted file
DocumentExportdocument_id, file_name, page_start, page_end, template_id, credits_used, extracted_dataExtracted document and parsed fields
FailedResultfile, errorFile that failed during extraction
BatchResultsucceeded, failed, totalContainer for batch results

Exceptions

All exceptions inherit from SuparseError.

ExceptionRaised When
SuparseErrorBase exception for all SDK errors
SuparseNetworkErrorNetwork connection fails or times out
SuparsePollingTimeoutErrorPolling exceeds maxPollAttempts
SuparseProcessingErrorDocument fails to process on the server
SuparseAPIErrorBase for HTTP error responses; has statusCode and responseBody
SuparseAuthError401/403 authentication or authorization error
SuparseNotFoundError404 resource not found
SuparseRateLimitError429 too many requests
SuparseServerError5xx server error
SuparseSDKErrorSDK fails to parse or handle the expected API response

extract() Parameters

ParameterTypeDefaultDescription
filesNode: string, Blob, File, URL, or array; browser/edge: Blob, File, URL, or arrayrequiredOne or more files to process
template_idstringundefinedTemplate ID (auto-detect if omitted)
splitbooleanfalseAuto-split multi-page documents
auto_approvebooleantrueSet to false to require human review in the Suparse UI
cleanupbooleanfalseDelete documents from server after extraction
onProgress(result) => voidundefinedCalled with each TaskExport or FailedResult as it completes

cleanup deletes the uploaded parent task documents after results have been fetched. Deleting a parent document also deletes its child documents server-side.

extractFolder() Parameters

extractFolder() is available only in @suparse/sdk/node.

ParameterTypeDefaultDescription
folderstringrequiredDirectory to scan
patternstringcurrently reservedPresent in the options type; current implementation scans supported files in the directory
template_idstringundefinedTemplate ID (auto-detect if omitted)
splitbooleanfalseAuto-split multi-page documents
auto_approvebooleantrueSet to false to require human review in the Suparse UI
cleanupbooleanfalseDelete documents from server after extraction
onProgress(result) => voidundefinedCalled with each result as it completes

Supported Files

ExtensionMIME Type
.pdfapplication/pdf
.jpg, .jpegimage/jpeg
.pngimage/png
.heicimage/heic
.heifimage/heif