Real-Time PDF Progress Streaming with SSE and X-Job-Id
In our earlier guide on polling vs webhooks for PDF status tracking, we covered the two most common approaches to monitoring PDF jobs. This article introduces the third option — Server-Sent Events (SSE) — which FUNBREW PDF API added for both batch jobs and single generation jobs in the May 31, 2026 release.
SSE is a good fit when you want to show live progress updates in a UI. No public webhook endpoint required, no repeated polling calls — just a persistent HTTP stream that pushes phase-by-phase progress as it happens.
Polling vs Webhook vs SSE
| Polling | Webhook | SSE | |
|---|---|---|---|
| Real-time updates | Delayed by interval | Yes | Yes |
| Requires public endpoint | No | Yes | No |
| Using it from a browser | Via your own backend | No | Via your own backend |
| Wasteful API calls | Yes | No | No |
| Mid-job progress (%) | No | No | Yes |
| Reconnection recovery | Custom logic needed | Retried on delivery failure (up to 3 attempts) | Resume with Last-Event-ID |
| Best for | CLI scripts, simple server jobs | Server-to-server completion notices | Progress bars, browser UI |
Polling means checking the batch status (GET /api/pdf/batch/{batch_id}). Single generation (/api/pdf/generate-from-html and friends) is synchronous: the PDF is ready when the response comes back.
SSE's key advantage: you get mid-job progress without needing a public HTTP endpoint. The API key must be sent in a header, though, and the browser's built-in EventSource cannot set headers (see below). To show progress in a browser, your own backend subscribes with the API key and relays the stream to the browser.
What Is Server-Sent Events
Server-Sent Events is a web standard that allows a server to push data over a persistent HTTP connection. The server responds with Content-Type: text/event-stream and streams newline-delimited events as the job progresses.
Key properties:
- Plain HTTP response — no protocol upgrade as with WebSocket
- Browser-native — events can be received with the
EventSourceAPI - Auto-reconnect — the HTML spec says clients reconnect when the connection is closed
- Gap recovery — on reconnect, the
Last-Event-IDheader tells the server the last ID you received
The SSE Endpoint
Endpoint Spec
GET /api/pdf/jobs/{jobId}/events
Accept: text/event-stream
Authorization: Bearer sk-xxxx # or X-API-Key: sk-xxxx
Last-Event-ID: <id> # Optional: resume from this event ID
There are two ways to get a jobId:
| Job type | How to get jobId |
|---|---|
| Batch generation | batch_id in the POST /api/pdf/batch response (201) |
Single generation (/generate-from-html etc.) |
X-Job-Id response header, or set your own X-Job-Id request header |
X-Job-Id works the same way on merge, compress, extract-text, and to-image. generate-from-template does not support X-Job-Id, so its progress cannot be streamed.
Authentication: send your PDF API key in the Authorization: Bearer or X-API-Key header. The key needs the download scope. This endpoint does not count against the per-minute rate limit or the monthly generation quota. On SaaS you can only subscribe to your own batches or to jobs submitted with your own API keys; anything else returns 404.
The X-Job-Id Header
Single generation is synchronous, so the job is already finished when the generation response comes back. To watch progress while it runs, use X-Job-Id and subscribe to SSE while the generation request is in flight.
- Set your own: generate a UUID, send it as the
X-Job-Idheader on the generation request, and open SSE with the same ID once that request has reached the server. You then get progress in real time - 🔴 Opening SSE first returns 404: on SaaS, the SSE endpoint returns 404 until the generation request reaches the server and the job ID is tied to your company. Send the generation request first and then subscribe, or wait briefly and retry on 404 (the link lasts one hour)
- Read it afterwards: if you omit
X-Job-Id, the server issues a UUID and returns it in theX-Job-Idresponse header. By then the job is finished, so opening SSE replays the retained history (up todone) in one go
Event Types and Payload
The stream sends a retry value right after connecting, then events named progress.
retry: 3000
id: 1748649600123-0
event: progress
data: {"phase":"queued","progress":0.0,"message":"received","data":{},"occurred_at":"2026-05-31T01:00:00+00:00"}
id: 1748649600456-0
event: progress
data: {"phase":"rendering","progress":0.2,"message":"rendering html","data":{},"occurred_at":"2026-05-31T01:00:01+00:00"}
id: 1748649600789-0
event: progress
data: {"phase":"done","progress":1.0,"message":"completed","data":{"filename":"...","download_url":"..."},"occurred_at":"2026-05-31T01:00:02+00:00"}
progress is a fraction from 0.0 to 1.0. For single generation, done carries filename and download_url in data. For batches, done (or failed when every item failed) carries batch_id, total_items, completed_items, and failed_items.
Phases:
phase |
Meaning |
|---|---|
queued |
Request received |
preprocessing |
Resolving the input PDF (merge, compress, extract-text, to-image only) |
rendering |
Rendering or processing |
postprocess |
Post-processing such as watermarks (single generation and batches) |
uploading |
Storing the generated PDF |
done |
Complete (terminal — server closes the stream) |
failed |
Failed (terminal — server closes the stream) |
The server closes the stream after sending done or failed. Close the connection on your side too when you receive a terminal phase (EventSource tries to reconnect to a closed connection).
Implementation Examples
Quick Test with curl
# Batch job
curl -N \
-H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
https://pdf.funbrew.cloud/api/pdf/jobs/<batch_id>/events
With -N (--no-buffer), each event is printed as it arrives. curl normally buffers its output, so without it the stream may not look real-time.
Watching a single generation (send the generation request first, subscribe while it runs):
# 1. Generate a job ID yourself
JOB_ID=$(uuidgen)
# 2. Submit the generation with the same job ID (synchronous, so run it in the background)
curl -s -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
-H "X-Job-Id: $JOB_ID" \
-H "Content-Type: application/json" \
-d '{"html":"<h1>Hello FUNBREW PDF</h1>"}' > result.json &
# 3. Give the request a moment to reach the server, then subscribe
sleep 1
curl -N -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
"https://pdf.funbrew.cloud/api/pdf/jobs/$JOB_ID/events"
Short HTML finishes in seconds, so the job may already be done when you subscribe. You still receive the retained history in one go.
Reading the job ID from the response header (useful for checking the history):
# Capture response headers
RESP=$(curl -sD - -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
-H "Content-Type: application/json" \
-d '{"html":"<h1>Hello FUNBREW PDF</h1>"}')
JOB_ID=$(echo "$RESP" | grep -i 'X-Job-Id' | cut -d' ' -f2 | tr -d '\r')
# Subscribe (the job is finished, so you get the queued-to-done history)
curl -N -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
"https://pdf.funbrew.cloud/api/pdf/jobs/$JOB_ID/events"
Server-Side Subscription (Node.js 18+, fetch)
Because the API key must go in a header, reading the stream with fetch is the reliable option on the server. This uses the built-in fetch in Node.js 18+ (no extra packages).
const baseUrl = 'https://pdf.funbrew.cloud';
const apiKey = process.env.FUNBREW_PDF_API_KEY;
async function streamJobEvents(jobId, onEvent) {
const res = await fetch(`${baseUrl}/api/pdf/jobs/${jobId}/events`, {
headers: {
Authorization: `Bearer ${apiKey}`,
Accept: 'text/event-stream',
},
});
if (!res.ok) throw new Error(`SSE HTTP ${res.status}`); // on 404, wait and retry
const decoder = new TextDecoder();
let buffer = '';
for await (const chunk of res.body) {
buffer += decoder.decode(chunk, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
const dataLine = block.split('\n').find((line) => line.startsWith('data: '));
if (!dataLine) continue; // e.g. the retry: line
const payload = JSON.parse(dataLine.slice(6));
onEvent(payload);
if (payload.phase === 'done' || payload.phase === 'failed') return payload;
}
}
}
const batchId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
const last = await streamJobEvents(batchId, (p) => {
console.log(`[${p.phase}] ${Math.round(p.progress * 100)}% — ${p.message}`);
});
process.exit(last?.phase === 'done' ? 0 : 1);
Browser EventSource API (relayed by your backend)
The only option the browser's EventSource constructor accepts is withCredentials; you cannot add headers such as Authorization. To keep your API key out of the browser as well, add a relay endpoint on your own backend (/progress/{jobId} in the example below). The backend subscribes with the API key using the fetch code above and passes the stream through to the browser.
const jobId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; // batch_id or X-Job-Id
// Relay endpoint on your own backend (it adds the API key)
const es = new EventSource(`/progress/${jobId}`);
es.addEventListener('progress', (event) => {
const payload = JSON.parse(event.data);
// Update progress bar (0.0 to 1.0)
updateProgressBar(payload.progress);
// Update status label
showStatus(payload.phase, payload.message);
// Close on terminal phases
if (payload.phase === 'done' || payload.phase === 'failed') {
es.close();
if (payload.phase === 'done') {
console.log('Done:', payload.data);
} else {
console.error('Failed:', payload.message);
}
}
});
es.onerror = (err) => {
// EventSource reconnects on its own and sends the last ID in the Last-Event-ID header.
// If your relay forwards that header to FUNBREW PDF API, the stream resumes where it left off.
console.warn('SSE error (reconnecting):', err);
};
The relay should pass the id:, event:, and data: lines through unchanged and forward the browser's Last-Event-ID header to FUNBREW PDF API.
@funbrew/pdf-client SDK
The JS SDK (@funbrew/pdf-client) has a subscribeToJob() method, but it cannot be used for SSE subscriptions at the moment. The SDK sends the API key as a query string (?api_key=), while the API reads the key only from headers, so the subscription fails authentication.
Use the SDK to send generation requests with an X-Job-Id, and subscribe to progress with the fetch example above.
import { PdfClient } from 'https://pdf.funbrew.cloud/sdk/pdf-client.esm.js';
// This holds your API key, so use it server-side (or in an internal tool where exposing the key is acceptable)
const client = new PdfClient({
baseUrl: 'https://pdf.funbrew.cloud',
apiKey: process.env.FUNBREW_PDF_API_KEY,
});
// 1. Decide the job ID first
const jobId = crypto.randomUUID();
// 2. Submit the job with the same ID (generateFromHtml sends it as the X-Job-Id header)
const pending = client.generateFromHtml(
{ html: '<h1>Hello FUNBREW PDF</h1>', options: { 'page-size': 'A4' } },
{ jobId }
);
// 3. Subscribe while it runs (streamJobEvents from above)
await new Promise((r) => setTimeout(r, 500));
await streamJobEvents(jobId, (p) => updateProgressBar(p.progress));
const result = await pending;
console.log('PDF ready:', result);
Single generation phase order: queued → rendering → postprocess → uploading → done (or failed)
Choosing the Right Approach
| Scenario | Recommended |
|---|---|
| Progress bar in a browser | SSE (relayed by your backend) |
| CLI script / cron job | Polling |
| Server-to-server completion notice | Webhook |
| No public endpoint available | SSE or polling |
| Long-running batches | SSE + Webhook |
| Short single generation | Synchronous API (no polling needed) |
| Tracking many jobs at once | Webhook (SSE holds one long-lived connection per job) |
Use SSE and webhooks together: SSE covers "showing progress while the user is watching", webhooks cover "telling your server the PDF is ready". Using SSE for the UI and webhooks to trigger backend processing keeps each part simple.
Production Considerations
The "PHP-FPM", "Nginx", and "environment variables" sections below apply when you run the Open edition on your own server. Nothing needs configuring when you use the SaaS (pdf.funbrew.cloud). If you relay the stream through your own backend, the same buffering advice applies to the proxy in front of your relay.
PHP-FPM Worker Usage
Each active SSE connection holds one PHP-FPM worker. If you expect many concurrent connections, make sure you have enough workers, for example by giving SSE a dedicated FPM pool with more workers.
Nginx Configuration
location /api/pdf/jobs/ {
proxy_pass http://app;
proxy_buffering off; # Buffering breaks real-time delivery
proxy_cache off;
proxy_read_timeout 3600s; # Allow long-lived connections
proxy_http_version 1.1;
proxy_set_header Connection '';
}
The response carries X-Accel-Buffering: no, so Nginx disables buffering for it (unless you told Nginx to ignore that header with proxy_ignore_headers). Setting proxy_buffering off explicitly is the safer option.
Timeouts and Max Duration
When a connection reaches the maximum duration (600 seconds by default), the server closes the stream. With EventSource auto-reconnect and Last-Event-ID, the stream resumes from where it left off.
| Environment variable | Default | Description |
|---|---|---|
PDF_PROGRESS_MAX_DURATION |
600 |
Max seconds per connection |
PDF_PROGRESS_POLL_MS |
500 |
How often the server checks for new events (ms) |
PDF_PROGRESS_TTL |
86400 |
How long progress history is kept in Redis (seconds) |
Gap Recovery with Last-Event-ID
With the Last-Event-ID header you get the stream from just after the last event ID you received. Browsers' EventSource adds this header automatically when reconnecting.
IDs are Redis Stream IDs (<milliseconds>-<sequence>). History is kept at roughly 1,000 events per job for 24 hours by default.
Handling Stale IDs
If Last-Event-ID is older than the oldest retained event, the server returns 410 Gone. Reconnect without Last-Event-ID to receive the retained history from the beginning. For batches you can also check the counts with GET /api/pdf/batch/{batch_id}.
Summary
FUNBREW PDF API's SSE streaming is the third option alongside polling and webhooks, and it is especially suited to real-time progress display.
- Send the API key in a header. To show progress in a browser, relay the stream through your own backend
- Works for batch and single jobs. For single jobs, subscribe with
X-Job-Idwhile the generation request is running Last-Event-IDgap recovery — reconnects resume where they left off- The SDK's
subscribeToJobcannot authenticate at the moment, so subscribe withfetch
Showing a progress bar via SSE during long batches while handling completion via webhooks is a practical setup for production.
Related Links
- Polling vs Webhook: PDF Status Tracking Guide — Detailed polling and webhook patterns
- JS SDK (@funbrew/pdf-client) Complete Guide — SDK features and limitations
- Resumable Upload with tus Guide — Reliable large file uploads
- API Documentation — Endpoint reference, authentication, rate limits
- Playground — Try PDF generation in your browser