# Background processing (/docs/background-processing)

Submit a document, save its job ID, and let your application continue working. You can check progress when needed or receive a webhook when processing finishes.

Use `documents.create` to wait for the result. Use `jobs.create` to submit now and retrieve it later. Both accept the same file and processing options; `timeoutMs` applies only to the completion wait in `documents.create`.

## Submit a background job [#submit-a-background-job]

Use the client and API key from the [SDK quickstart](/docs/sdk-quickstart):

```js
import { Pagelet } from "@pagelet-ai/sdk"

const client = new Pagelet()
const job = await client.jobs.create({ file: "statement.pdf" })

console.log(job.id)
```

Save the returned ID with your application's record. The method returns after submission, without waiting for content recovery.

## Check progress and read the result [#check-progress-and-read-the-result]

Given the `job.id` returned above:

```js
const status = await client.jobs.get(job.id)
console.log(status.status)

if (status.result_available) {
  const result = await client.jobs.result(job.id)
  console.log(result.document.filename)
}
```

`jobs.get` returns the current status. `jobs.result` retrieves available content. Neither method waits for processing to finish.

<details>
<summary>Polling example</summary>

This example checks the submitted job every two seconds until processing finishes:

```js
import { setTimeout as delay } from "node:timers/promises"

const finalStatuses = new Set(["completed", "completed_with_warnings", "failed", "rejected"])
let status = await client.jobs.get(job.id)

while (!finalStatuses.has(status.status)) {
  await delay(2000)
  status = await client.jobs.get(job.id)
}

if (!status.result_available) {
  throw new Error(status.detail?.message ?? status.status)
}

const result = await client.jobs.result(job.id)
console.log(result.document.filename)
```

</details>

| Status                    | Meaning                                              |
| ------------------------- | ---------------------------------------------------- |
| `waiting_for_upload`      | The job is waiting for the file submission to finish |
| `validating`              | The document is being checked and prepared           |
| `processing`              | Page content is being recovered                      |
| `completed`               | Processing finished successfully                     |
| `completed_with_warnings` | Processing finished with content warnings            |
| `failed`                  | Processing failed; a result may still be available   |
| `rejected`                | The document was not accepted for processing         |

The last four statuses are final. `result_available` tells you whether there is content to retrieve, including after a failed job. Processing completion is separate from Search readiness and webhook delivery.

## Set up a webhook [#set-up-a-webhook]

As the workspace owner, open **Settings → Webhooks**. Select **Set up signing**, then **Create secret**. Save the signing secret on your server; it is shown once. Add your publicly reachable HTTPS address under **Default endpoint**.

New submissions inherit that endpoint. To choose a different destination for one document, set `webhookUrl`:

```js
const job = await client.jobs.create({
  file: "statement.pdf",
  webhookUrl: "https://your-app.example/webhooks/documents",
})
```

Replace the example URL with your endpoint. Signing must already be configured for the workspace. Set `webhookUrl: null` to disable delivery for a submission. Changing the workspace default does not move deliveries already assigned to another destination.

## Verify a notification [#verify-a-notification]

A terminal notification has `event_type: "job.status_updated"`, a stable `event_id`, a `created_at` timestamp, and a `job` object with the same fields as `jobs.get`. It announces a processing outcome, which can be successful, failed, or rejected. It does not contain the full page content.

Use these request headers to verify the notification:

| Header              | Purpose                                             |
| ------------------- | --------------------------------------------------- |
| `webhook-id`        | Stable event identifier                             |
| `webhook-timestamp` | Delivery timestamp in Unix seconds                  |
| `webhook-signature` | Signature used to authenticate the body and headers |

Install `standardwebhooks` to verify notifications with your workspace's signing secret:

```sh
npm install standardwebhooks
```

Store the signing secret from Settings in your server's `PAGELET_WEBHOOK_SECRET` environment variable. This helper verifies a standard Web `Request` before returning its parsed event:

```js
import { Webhook } from "standardwebhooks"

const verifier = new Webhook(process.env.PAGELET_WEBHOOK_SECRET)

export async function verifyWebhook(request) {
  const body = await request.text()
  return verifier.verify(body, Object.fromEntries(request.headers))
}
```

Pass the original body and headers to verification before parsing the JSON. Reject the request if verification throws. Use the webhook signing secret, not your API key.

## Handle the event once [#handle-the-event-once]

Notifications can arrive more than once. Use `event_id` to recognize duplicates and return `2xx` once your application has durably accepted the event. A duplicate that was already accepted can receive `2xx` again.

The verified event includes `job.result_available`. When it is true, retrieve the content with `jobs.result(event.job.id)`. Otherwise, the job's status and detail describe the failure or rejection.

## Delivery and recovery [#delivery-and-recovery]

Your endpoint should acknowledge accepted events promptly. Delivery has a 15-second attempt budget and supports up to eight attempts with increasing delays. A `2xx` response marks the event delivered. HTTP `410` stops delivery; redirects are not followed. Other unsuccessful responses can be retried within the attempt limit.

Retries retain the event ID and use a new delivery timestamp and signature. Deduplicate by event ID, not by signature. Webhook delivery failure does not undo a completed document result; you can retrieve job status and content directly.

If you rotate the signing secret, new attempts and retries use the replacement. An attempt already sending may still use the previous secret, so coordinate the change with your receiver.

If an awaited `documents.create` call times out, processing may still finish. Use the job ID carried by the timeout to check the existing submission. Do not create another document merely because the wait ended.
