> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Add transcripts and downloads to a Cloudflare Worker

> A working Cloudflare Workers recipe: start a transcript or download from a Worker, poll for long jobs, and verify Importly webhooks with Web Crypto. No binaries or containers needed.

A Worker can't run a binary or start a subprocess, so a downloader or ffmpeg can't run inside one. You don't need either: the Worker sends the link to Importly over HTTPS and gets back the transcript, a link to the file, or the metadata. This recipe is one Worker with three routes: start a transcript, check on a long one, and receive the webhook.

## 1. Add your key as a secret

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and store it as a Worker secret, so it never sits in `wrangler.toml` or your repo:

```bash theme={null}
npx wrangler secret put IMPORTLY_API_KEY
```

For `wrangler dev`, put the same value in a `.dev.vars` file next to `wrangler.toml` and keep that file out of git:

```bash .dev.vars theme={null}
IMPORTLY_API_KEY=your_api_key
```

## 2. The Worker

`POST /transcribe` sends the link to Importly. `"mode": "auto"` uses the video's captions and falls back to speech-to-text when there are none. `wait` holds the request until the transcript is ready, so a captioned video usually comes back in this one call. Time spent waiting on `fetch` doesn't count against a Worker's CPU limit.

```ts src/index.ts theme={null}
interface Env {
  IMPORTLY_API_KEY: string
  IMPORTLY_WEBHOOK_SECRET?: string
}

const API = 'https://api.importly.io'

// Same shape for a finished, failed or still-running job
const toResult = (data: any) => ({
  jobId: data.jobId,
  status: data.status,
  text: data.result?.text,
  segments: data.result?.data?.segments,
  message: data.message,
  code: data.code,
})

const callImportly = async (env: Env, path: string, init: RequestInit = {}) => {
  const res = await fetch(`${API}${path}`, {
    ...init,
    headers: { Authorization: `Bearer ${env.IMPORTLY_API_KEY}`, 'Content-Type': 'application/json' },
  })
  const body: any = await res.json()
  if (!res.ok || !body.success) {
    return Response.json({ status: 'failed', message: body.error, code: body.code }, { status: res.status })
  }
  return Response.json(toResult(body.data))
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const { pathname, searchParams } = new URL(request.url)

    if (request.method === 'POST' && pathname === '/transcribe') {
      const { url } = (await request.json()) as { url: string }
      // wait up to 25s for the result; cap speech-to-text on long videos at $0.50
      return callImportly(env, '/transcribe', {
        method: 'POST',
        body: JSON.stringify({ url, mode: 'auto', wait: 25, maxCostDollars: 0.5 }),
      })
    }

    if (request.method === 'GET' && pathname === '/transcribe/status') {
      const id = searchParams.get('id') ?? ''
      return callImportly(env, `/transcribe/status?id=${encodeURIComponent(id)}`)
    }

    if (request.method === 'POST' && pathname === '/webhooks/importly') {
      return handleWebhook(request, env)
    }

    return new Response('Not found', { status: 404 })
  },
}
```

A rejected request (a bad link, a key problem, or a low balance) comes back with an HTTP error and an `error` message. A job that fails later, for example because the video is private, comes back with `status: "failed"`, a `code` and a `message`. See [Error handling](/docs/error-handling.md).

## 3. Poll if it's still running

Long videos without captions take longer than `wait`. Then the response has `status: "queued"` or `"running"` and a `jobId`. Have your frontend call `GET /transcribe/status?id=<jobId>` every few seconds until the status is `completed` or `failed`:

```ts theme={null}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

let job = await fetch('/transcribe', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ url }),
}).then((res) => res.json())

while (job.status === 'queued' || job.status === 'running') {
  await sleep(3000)
  job = await fetch(`/transcribe/status?id=${job.jobId}`).then((res) => res.json())
}
```

`segments` holds the same transcript with `start` and `end` times in seconds, for captions, chapters or search.

## 4. In production: a webhook, verified with Web Crypto

When the transcript belongs to a record in your database (D1, KV, Supabase), don't keep anyone waiting. Start the job with a `webhookUrl` pointing at your Worker and save the result when Importly calls back:

```ts theme={null}
body: JSON.stringify({ url, mode: 'auto', maxCostDollars: 0.5, webhookUrl: 'https://your-worker.your-subdomain.workers.dev/webhooks/importly' }),
```

Every delivery is signed. Copy the **Webhook signing secret** (it starts with `whsec_`) from the [API key page](https://www.importly.io/dashboard/api-key) and add it as a second secret:

```bash theme={null}
npx wrangler secret put IMPORTLY_WEBHOOK_SECRET
```

Workers have no `node:crypto` by default, so this check uses Web Crypto. `crypto.subtle.verify` compares the signature in constant time, which is what you want here. The handler then takes only the `jobId` from the payload and reads the result from the API with your key:

```ts src/index.ts theme={null}
const hexToBytes = (hex: string) => {
  if (!/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) return null
  return new Uint8Array(hex.match(/../g)!.map((byte) => parseInt(byte, 16)))
}

const verifyImportlySignature = async (header: string | null, rawBody: string, secret: string, toleranceSeconds = 300) => {
  if (!header) return false
  const parts = header.split(',').map((part) => part.trim().split('='))
  const timestamp = Number(parts.find(([key]) => key === 't')?.[1])
  if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false

  const encoder = new TextEncoder()
  const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'])
  const signed = encoder.encode(`${timestamp}.${rawBody}`)

  for (const [name, value] of parts) {
    const signature = name === 'v1' ? hexToBytes(value ?? '') : null
    if (signature && (await crypto.subtle.verify('HMAC', key, signature, signed))) return true
  }
  return false
}

const handleWebhook = async (request: Request, env: Env) => {
  // read the raw text: the signature covers the exact bytes Importly sent
  const rawBody = await request.text()
  if (!env.IMPORTLY_WEBHOOK_SECRET || !(await verifyImportlySignature(request.headers.get('Importly-Signature'), rawBody, env.IMPORTLY_WEBHOOK_SECRET))) {
    return new Response(null, { status: 400 })
  }

  const { data } = JSON.parse(rawBody)
  if (data?.type !== 'transcribe' || typeof data.jobId !== 'string') return new Response(null, { status: 200 })

  const res = await fetch(`${API}/transcribe/status?id=${encodeURIComponent(data.jobId)}`, {
    headers: { Authorization: `Bearer ${env.IMPORTLY_API_KEY}` },
  })
  const body: any = await res.json()
  if (!body.success) return new Response(null, { status: 200 })

  const job = body.data
  if (job.status === 'completed') {
    // find your record by job.jobId and save job.result.text and job.result.data.segments
  }
  if (job.status === 'failed') {
    // mark the record failed with job.code and job.message
  }

  return new Response(null, { status: 200 })
}
```

Each job gets one delivery and no retries, so also check jobs that have been pending for a few minutes with the status endpoint (a [Cron Trigger](https://developers.cloudflare.com/workers/configuration/cron-triggers/) works well for that). The `Importly-Webhook-Id` header is the same for every delivery of a job's outcome, so you can store it and skip repeats. The webhook URL must be public `https://`, so `wrangler dev` on `localhost` gets nothing: use polling in development. See [Webhooks](/docs/webhooks.md).

## Downloading the file instead

For the video or audio file itself, send the link to [`POST /import`](/docs/endpoints/import) and read [`GET /import/status`](/docs/endpoints/import-status) the same way. The finished job has `result.mediaUrl`, a link to the file that's valid for 7 days. Set `includeVideo: false` for audio only. To keep files, set `store: true` and have each import copied to your own bucket, including Cloudflare R2 ([recipe](/docs/integrations/save-to-bucket.md)). `/import` has no `wait`, so use polling or a webhook. See [Downloads](/docs/features/downloads.md).

> [!NOTE]
>
> A transcript from captions costs $0.003. Speech-to-text for a video without captions is $0.01 per minute, and `maxCostDollars` stops a long one before it's charged. Try it free, no card required. See [Pricing & credits](/docs/billing.md).

## Let your agent write it

Using Claude Code or Cursor on this Worker? Connect the [MCP server](/docs/integrations/mcp.md) and ask it to add transcripts with Importly: it reads the same integration guide and can test with a real link first. See [Build with your agent](/docs/integrations/build-with-your-agent.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.