@funbrew/pdf-client: Browser SDK for PDF, tus Upload and SSE
Separate from the Node.js SDK @funbrew/pdf, @funbrew/pdf-client is a browser-focused JavaScript SDK served from https://pdf.funbrew.cloud/sdk/. It brings three capabilities together in one package:
- tus.io resumable uploads — automatic retries at the intervals you configure
- SSE progress —
subscribeToJob(), based onEventSource(currently cannot authenticate from a browser; a working alternative is shown below) - PDF generation and transformation — generate from HTML/URL/Markdown, plus compress, merge, extract text, and convert to images
@funbrew/pdf vs @funbrew/pdf-client: Which One to Use
Before diving in, here is the key distinction to avoid confusion with the Node.js SDK:
@funbrew/pdf |
@funbrew/pdf-client |
|
|---|---|---|
| Runtime | Node.js 18+ (server-side) | Browser (client-side) |
| Install | npm install @funbrew/pdf |
CDN (/sdk/pdf-client.umd.js / /sdk/pdf-client.esm.js). Not published on npm |
| tus upload | No | Yes — resumable, parallel-capable |
| SSE progress | No | subscribeToJob() (currently fails authentication; see below) |
| Primary use case | Next.js API routes, Lambda functions | File drop UIs, in-browser form submissions |
| Type definitions | Bundled with npm package | CDN at /sdk/types/index.d.ts |
Rule of thumb: server-side code uses @funbrew/pdf; browser code uses @funbrew/pdf-client. Keep in mind that an API key placed in the browser is visible to users (see below).
Installation
CDN (script tag)
Drop this into any HTML page to get the UMD build. The PdfClient class is exposed under the global PdfClient:
<script src="https://pdf.funbrew.cloud/sdk/pdf-client.umd.js"></script>
<script>
const client = new PdfClient.PdfClient({
baseUrl: 'https://pdf.funbrew.cloud',
apiKey: 'sk-...',
});
</script>
ESM (<script type="module">)
With native browser ES modules you can import the ESM build straight from its URL:
<script type="module">
import { PdfClient } from 'https://pdf.funbrew.cloud/sdk/pdf-client.esm.js';
const client = new PdfClient({
baseUrl: 'https://pdf.funbrew.cloud',
apiKey: 'sk-...',
});
</script>
TypeScript type definitions
Type definitions are served at https://pdf.funbrew.cloud/sdk/types/index.d.ts. paths in tsconfig.json resolves relative to the tsconfig (or baseUrl), so a URL cannot be used there. Download the file into your repository and point paths at it:
{
"compilerOptions": {
"paths": {
"@funbrew/pdf-client": ["./types/funbrew-pdf-client/index.d.ts"]
}
}
}
paths only changes how types are resolved, not where the import goes at runtime. At runtime, load the SDK from the CDN URL above.
Initialization
const client = new PdfClient({
baseUrl: 'https://pdf.funbrew.cloud', // a trailing slash is stripped automatically
apiKey: 'sk-...', // sent as the X-API-Key header
});
All PdfClientOptions fields:
interface PdfClientOptions {
baseUrl: string; // e.g. 'https://pdf.funbrew.cloud'
apiKey: string; // your PDF API key
fetch?: typeof fetch; // swap in a custom fetch (useful for testing)
}
PDF Generation
The SDK wraps the HTML, URL, and Markdown endpoints (/api/pdf/generate-from-html and friends). The first argument becomes the JSON request body as-is, so pass options with the same keys as the API (options.page-size, options.orientation, and so on).
// Generate from HTML
const result = await client.generateFromHtml({
html: '<h1>Invoice #1234</h1><p>Total: $500.00</p>',
options: { 'page-size': 'A4' },
});
console.log(result.download_url); // https://pdf.funbrew.cloud/api/pdf/download/<filename> (needs the API key)
console.log(result.public_url); // https://pdf.funbrew.cloud/dl/<token> (public, no key)
// Generate from a URL (landscape)
const fromUrl = await client.generateFromUrl({
url: 'https://example.com/report',
options: { 'page-size': 'A4', orientation: 'Landscape' },
});
// Generate from Markdown (theme is top-level: business / modern / minimal / academic / creative)
const fromMd = await client.generateFromMarkdown({
markdown: '# Report\n\nContent here...',
theme: 'business',
});
The GenerateResult type declared by the SDK:
interface GenerateResult {
filename: string;
download_url: string;
file_size: number; // bytes
expires_at?: string | null;
job_id?: string;
[key: string]: unknown; // other fields the API returns, such as public_url and max_downloads
}
download_url (/api/pdf/download/...) requires the API key header, so pasting it into an <a href> will not work. To give users a link in the browser, use public_url (/dl/...), which the generation endpoints return.
Resumable File Uploads (uploadFile)
uploadFile() uploads to /api/pdf/uploads with the tus protocol (resumable uploads over HTTP). It is built on tus-js-client and retries on network errors at the retryDelays intervals.
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const upload = await client.uploadFile(file, {
chunkSize: 5 * 1024 * 1024, // 5 MB chunks (the SDK default)
onProgress: (sent, total) => {
const pct = Math.round((sent / total) * 100);
document.querySelector('#progress').textContent = `${pct}%`;
},
});
console.log(upload.key); // UUID — pass as upload_id to merge/compress
console.log(upload.url); // tus Location URL
console.log(upload.size); // file size in bytes
All UploadOptions fields:
interface UploadOptions {
chunkSize?: number; // default: 5 MB
retryDelays?: number[]; // default: [0, 1000, 3000, 5000, 10000]
metadata?: Record<string, string>; // added to Upload-Metadata (filename / filetype are automatic)
onProgress?: (sent: number, total: number) => void;
signal?: AbortSignal; // abort support
parallelUploads?: number; // number of parallel uploads (default: 1)
}
Parallel Uploads (High-RTT Environments)
With parallelUploads set to 2 or more, the file is split into N partial uploads via the tus Concatenation extension, sent in parallel, and joined into one file on the server. This can improve throughput on high-RTT connections.
const upload = await client.uploadFile(file, {
parallelUploads: 4, // send 4 parts concurrently
onProgress: (sent, total) => console.log(`${sent}/${total}`),
});
Note: If the server's tus storage is in s3-multipart mode, parallel uploads (Upload-Concat) return a 400 error. Only local mode supports them.
Aborting with AbortSignal
const controller = new AbortController();
const uploadPromise = client.uploadFile(file, {
signal: controller.signal,
onProgress: (sent, total) => console.log(`${sent}/${total}`),
});
// Wire up a cancel button
document.querySelector('#cancel').addEventListener('click', () => {
controller.abort();
});
try {
const upload = await uploadPromise;
} catch (err) {
if (err.name === 'AbortError') console.log('Upload cancelled');
}
Progress Subscription (SSE)
When you send an X-Job-Id header to the merge, compress, to-image, or generation endpoints, progress events for that ID are streamed on GET /api/pdf/jobs/{jobId}/events (SSE). See the SSE progress guide for details.
Current limitation of subscribeToJob()
The SDK's subscribeToJob() uses EventSource. Because EventSource cannot set request headers, the SDK puts the API key in the ?api_key= query parameter. The server, however, only accepts the key in headers (Authorization: Bearer or X-API-Key) and returns 401 for a query-string key. As a result, calling subscribeToJob() from a browser currently delivers no progress events.
There is a second constraint: the SSE stream only works after the job has been submitted. The server records "this jobId belongs to this company" when it receives the API request, and returns 404 for any jobId without that record.
Reading SSE with fetch
fetch can set headers, so reading the stream with it does work from the browser. Start the subscription right after submitting the job, and retry briefly while it returns 404.
const BASE_URL = 'https://pdf.funbrew.cloud';
const API_KEY = 'sk-...';
async function subscribeWithFetch(jobId, onProgress) {
const url = `${BASE_URL}/api/pdf/jobs/${jobId}/events`;
for (let attempt = 0; attempt < 10; attempt++) {
const res = await fetch(url, {
headers: { 'X-API-Key': API_KEY, Accept: 'text/event-stream' },
});
if (res.status === 404) {
// The job has not been recorded yet; wait and retry
await new Promise((r) => setTimeout(r, 300));
continue;
}
if (!res.ok) throw new Error(`SSE HTTP ${res.status}`);
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) return null;
buffer += value;
let sep;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
const line = block.split('\n').find((l) => l.startsWith('data: '));
if (!line) continue;
const event = JSON.parse(line.slice(6));
onProgress(event);
if (event.phase === 'done' || event.phase === 'failed') {
await reader.cancel();
return event;
}
}
}
}
throw new Error('job not found');
}
Each event's data has this shape. progress is a fraction from 0 to 1 (multiply by 100 for a percentage).
interface ProgressEventPayload {
phase: string; // 'queued' | 'preprocessing' | 'rendering' | 'postprocess' | 'uploading' | 'done' | 'failed'
progress: number; // 0–1
message?: string | null;
data?: Record<string, unknown>;
occurred_at: string; // ISO 8601
}
Phase transitions (postprocess appears only for generation and batch jobs):
queued → preprocessing → rendering → (postprocess) → uploading → done
↘ failed
Full Pipeline: Upload → Compress → Done
Here is a complete function that takes a file from the user, uploads it, and compresses it. The compress endpoint does not respond until the work is finished, so the result itself comes back from compress(); SSE is used only to show intermediate progress. See also the tus resumable upload guide.
async function compressPdfWithProgress(file, qualityLevel = 'medium') {
const jobId = crypto.randomUUID();
// 1. UI update helper
const updateUI = (phase, pct) => {
document.querySelector('#status').textContent = `${phase} ${pct}%`;
};
// 2. Upload via tus
updateUI('uploading', 0);
const upload = await client.uploadFile(file, {
onProgress: (sent, total) =>
updateUI('uploading', Math.round((sent / total) * 100)),
});
// 3. Submit the compress job (with X-Job-Id), then subscribe to SSE
const compressing = client.compress(
{ upload_id: upload.key, quality: qualityLevel },
{ jobId },
);
subscribeWithFetch(jobId, ({ phase, progress }) =>
updateUI(phase, Math.round(progress * 100)),
).catch(() => { /* progress display only, keep going on failure */ });
// 4. The result comes back from compress()
const result = await compressing;
updateUI('done', 100);
return result; // filename, download_url, original_size, compressed_size, savings_percent ...
}
// Usage
const fileInput = document.querySelector('#pdf-file');
const result = await compressPdfWithProgress(fileInput.files[0], 'high');
The compress result's download_url (/api/pdf/download/...) requires the API key. To let the user save it in the browser, fetch it with the X-API-Key header and link to a Blob URL:
const res = await fetch(result.download_url, { headers: { 'X-API-Key': API_KEY } });
const link = document.querySelector('#download');
link.href = URL.createObjectURL(await res.blob());
link.download = result.filename;
link.style.display = 'block';
Chaining Uploads with Other Operations
upload.key works as upload_id for merge, extractText, and toImage as well. For compress, extractText, and toImage, filename (server-stored) and upload_id (tus upload) are mutually exclusive — supply one or the other. For merge, filenames and upload_ids combined must total 2 to 50 files.
const upload = await client.uploadFile(file);
const anotherUpload = await client.uploadFile(anotherFile);
// Merge multiple PDFs
const merged = await client.merge({
upload_ids: [upload.key, anotherUpload.key],
});
// Extract text
const extracted = await client.extractText({
upload_id: upload.key,
});
// Convert to images (format: png / jpg, dpi: 72–1200, default 150)
const images = await client.toImage({
upload_id: upload.key,
format: 'png',
dpi: 150,
});
console.log(images.images); // per page: { page, filename, download_url, format, file_size }
Merge, compress, to-image, and text extraction are SaaS-edition APIs gated by plan features (all three current plans, Free, Pro and Business, include them). A plan without the feature gets a 403.
Error Handling
When the API returns a failure, the SDK throws an Error with err.status (HTTP status) and err.response (response JSON) attached. err.message is the response's message.
try {
const result = await client.compress({
upload_id: 'invalid-id',
quality: 'medium',
});
} catch (err) {
console.error(err.message); // e.g. "Upload not found: invalid-id"
console.error(err.status); // 422
console.error(err.response); // { success: false, message: 'Upload not found: invalid-id' }
}
Failures from uploadFile() are tus-js-client errors passed through as-is and do not carry err.status.
Upload Retry Behavior
uploadFile() retries at [0, 1000, 3000, 5000, 10000] ms intervals by default (the array length is the maximum number of attempts). To customize:
const upload = await client.uploadFile(file, {
retryDelays: [0, 2000, 5000, 10000, 30000], // longer waits
});
TypeScript Support
The SDK is written in TypeScript and exports its main types. With the paths setting above, you can import them by package name:
import type {
PdfClientOptions,
UploadResult,
UploadOptions,
GenerateResult,
ProgressEventPayload,
SubscribeOptions,
} from '@funbrew/pdf-client';
With proper types in place, onProgress callbacks and result.download_url accesses get full IDE autocompletion and type checking.
Security Considerations
Because @funbrew/pdf-client runs in the browser, the API key is visible to end users.
- Dashboard-issued keys have full permissions: the dashboard currently has no scope (permission) selection, so a key issued there can generate, download, and manage. If you put it in the browser, assume anyone can do all of that with it.
- Backend proxy: Route requests through your own API (
browser → your server → FUNBREW PDF). This keeps the API key server-side and is the recommended setup for production. - Generation and compression count against your company's monthly quota and per-minute limit. On public pages, add per-user limits on your side.
Live Demo
The SDK Playground (/sdk-playground) lets you enter an API key and try the flow in a browser: drop a file, upload via tus, compress, and see the result. The "compress + SSE 購読" button uses subscribeToJob(), so because of the limitation above it currently receives no progress events.
The Playground is useful for experimenting with HTML templates before integrating them via the SDK.
Summary
@funbrew/pdf-client consolidates three capabilities into a single browser SDK:
| Feature | Method / Detail |
|---|---|
| Resumable upload | uploadFile() — tus, auto-retry, parallel-capable |
| SSE progress | subscribeToJob() — currently fails authentication; read SSE with fetch instead |
| PDF generation + ops | generateFromHtml(), compress(), merge(), and more |
For server-side TypeScript patterns using the Node.js SDK, see the TypeScript PDF guide. For a deep dive on SSE mechanics, read the SSE progress streaming guide. For everything about resumable uploads, visit the tus resumable upload guide.
Browse use cases to see how other teams are integrating PDF generation into their products.