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

# Use Importly in BullMQ jobs

> Transcribe or download any video or audio link from a BullMQ worker in a Node app, with a shared rate limit, waits that respect 429s, and status checks that never start the same job twice.

If your Node app hands video or podcast links to a BullMQ worker, the media job is the one that breaks once it runs on a server: sites block datacenter IPs, and many videos have no captions to read. Call Importly from the worker instead. It returns the transcript, a download link for the file, or the video's details, for links from YouTube, TikTok, Instagram, X, podcasts and 1,000+ other sites.

Long imports can take a few minutes, so don't hold a worker for them. This page uses two queues: `importly-start` starts the job, and `importly-check` checks its status every 20 seconds until it's done. A check only ever reads the status, so a retry never starts the job twice.

Tested with BullMQ 6, ioredis 6 and Node 22. The code is TypeScript; drop the types for plain JavaScript.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once). Add it as `IMPORTLY_API_KEY` to the environment your workers run in, and to `.env` for local development:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
REDIS_URL=redis://localhost:6379
```

```bash theme={null}
npm install bullmq ioredis
```

BullMQ 6 no longer installs ioredis for you, so add it yourself.

## 2. A small client

A `429` or a `5xx` throws `RetryLater` with how long to wait: the `retryAfter` the API sent, or 30 seconds. A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) won't change on a retry, so it throws BullMQ's `UnrecoverableError` and the job fails without using up its attempts:

```ts importly.ts theme={null}
import { UnrecoverableError } from 'bullmq'

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

// A 429 or 5xx: the same request can work after `ms`
export class RetryLater extends Error {
  constructor(message: string, public status: number, public ms: number) {
    super(message)
  }
}

export type Job = {
  jobId: string
  status: 'queued' | 'running' | 'completed' | 'failed'
  result?: Record<string, any>
  code?: string
  message?: string
}

export const call = async (path: string, body?: object): Promise<Job> => {
  const res = await fetch(`${API}${path}`, {
    method: body ? 'POST' : 'GET',
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: body ? JSON.stringify(body) : undefined,
  })
  const data = await res.json()
  if (res.ok && data.success) return data.data

  const message = `Importly ${res.status} ${data.code ?? ''}: ${data.error ?? 'request failed'}`
  if (res.status === 429) throw new RetryLater(message, 429, (data.retryAfter ?? 60) * 1000)
  if (res.status >= 500) throw new RetryLater(message, res.status, 30_000)
  // a 400 (bad link), 401 (wrong key) or 402 (balance too low): a retry won't change it
  throw new UnrecoverableError(message)
}
```

## 3. The queues

Pass one ioredis connection with `maxRetriesPerRequest: null`, which BullMQ workers need. A `5xx` on either queue is retried up to five times with backoff:

```ts queues.ts theme={null}
import { Queue } from 'bullmq'
import { Redis } from 'ioredis'

// maxRetriesPerRequest: null is what BullMQ workers need
export const connection = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379', { maxRetriesPerRequest: null })

export type StartData = { recordId: string; kind: 'transcribe' | 'import'; url: string }
export type CheckData = { recordId: string; kind: 'transcribe' | 'import'; jobId: string; checks: number }

export const startQueue = new Queue<StartData>('importly-start', {
  connection,
  defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 30_000 } },
})

export const checkQueue = new Queue<CheckData>('importly-check', {
  connection,
  defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 30_000 } },
})
```

## 4. The workers

`"mode": "auto"` uses the video's captions and falls back to speech-to-text when it has none. `wait: true` holds the request open for up to 30 seconds, so a transcript from captions usually comes back from the first call and is saved straight away. Anything still `queued` or `running` goes to `importly-check`:

```ts worker.ts theme={null}
import { DelayedError, Worker } from 'bullmq'
import { call, RetryLater, type Job } from './importly'
import { checkQueue, connection, type CheckData, type StartData } from './queues'
import { saveResult } from './save-result'

const START_BODY = {
  transcribe: (url: string) => ({
    url,
    mode: 'auto', // captions, or speech-to-text when there are none
    wait: true, // captions usually come back within the 30-second wait
    maxCostDollars: 1,
  }),
  import: (url: string) => ({
    url,
    videoQuality: '720p', // a ceiling: lower if the source has no 720p
    maxCostDollars: 0.5, // the most this one file may cost
  }),
}

const STATUS_PATH = { transcribe: '/transcribe/status', import: '/import/status' }

const finishOrCheck = async (recordId: string, kind: StartData['kind'], job: Job) => {
  if (job.status === 'queued' || job.status === 'running') {
    // the job id makes a second add for the same Importly job a no-op
    await checkQueue.add('check', { recordId, kind, jobId: job.jobId, checks: 0 }, { delay: 20_000, jobId: job.jobId })
  } else {
    await saveResult(recordId, kind, job)
  }
}

// Starts jobs. The limiter keeps every worker together under 240 imports an hour.
export const startWorker = new Worker<StartData>(
  'importly-start',
  async (task) => {
    try {
      const job = await call(`/${task.data.kind}`, START_BODY[task.data.kind](task.data.url))
      await finishOrCheck(task.data.recordId, task.data.kind, job)
    } catch (err) {
      if (err instanceof RetryLater && err.status === 429) {
        // a 429: pause the whole queue for retryAfter, without using up an attempt
        await startWorker.rateLimit(err.ms)
        throw Worker.RateLimitError()
      }
      throw err
    }
  },
  { connection, limiter: { max: 4, duration: 60_000 } },
)

// Checks a job every 20 seconds, for up to an hour
export const checkWorker = new Worker<CheckData>(
  'importly-check',
  async (task, token) => {
    const { recordId, kind, jobId, checks } = task.data
    let wait = 20_000
    try {
      const job = await call(`${STATUS_PATH[kind]}?id=${encodeURIComponent(jobId)}`)
      if (job.status === 'completed' || job.status === 'failed') return saveResult(recordId, kind, job)
      if (checks >= 180) throw new Error(`Importly job ${jobId} still ${job.status} after an hour`)
    } catch (err) {
      if (!(err instanceof RetryLater)) throw err
      wait = err.ms // a 429 or 5xx: check again after the wait the API asked for
    }
    await task.updateData({ ...task.data, checks: checks + 1 })
    await task.moveToDelayed(Date.now() + wait, token!)
    throw new DelayedError()
  },
  { connection, concurrency: 20 },
)
```

Two BullMQ features do the waiting:

* On a `429` from a start, `startWorker.rateLimit()` pauses the whole start queue for `retryAfter`, on every worker, and `Worker.RateLimitError()` puts the job back without counting an attempt.
* A check that finds the job still running moves itself to the delayed set with `moveToDelayed` and throws `DelayedError`, so the same BullMQ job comes back in 20 seconds. It does the same on a `429` or `5xx`, waiting as long as the API asked.

`saveResult` is yours:

```ts save-result.ts theme={null}
import type { Job } from './importly'

export const saveResult = async (recordId: string, kind: 'transcribe' | 'import', job: Job) => {
  if (job.status === 'failed') {
    // job.code and job.message say why, for example VIDEO_PRIVATE
    return db.media.update({ where: { id: recordId }, data: { status: 'failed', error: job.code } })
  }
  const data = kind === 'transcribe'
    ? { status: 'done', transcript: job.result!.text }
    : { status: 'done', fileUrl: job.result!.mediaUrl }
  await db.media.update({ where: { id: recordId }, data })
}
```

`db` stands for your ORM. A transcript has `result.text`, plus `result.data.segments` with start and end times. An import has `result.mediaUrl`, a link to the file that's valid for 7 days, so copy the file to your storage if you keep it, or connect your bucket once and import with `store: true` ([Save to your bucket](/docs/integrations/save-to-bucket.md)).

## Run it

Add a job from your API route once the record is saved:

```ts theme={null}
import { startQueue } from './queues'

const media = await db.media.create({ data: { url, status: 'pending' } })
await startQueue.add('transcribe', { recordId: media.id, kind: 'transcribe', url })
```

Run the workers in their own process, for example `node --env-file=.env --import tsx worker.ts`, next to your web server. They work on any host that runs a long-lived Node process and has Redis: Fly.io, Railway, Render, a container or a VM. On serverless hosts without a long-lived process, use [Trigger.dev](/docs/integrations/trigger-dev.md) or [Inngest](/docs/integrations/inngest.md) instead.

## Notes

`POST /import` and `POST /transcribe` allow 240 requests per hour per key. BullMQ's `limiter` counts across every worker on the queue, so `max: 4` per minute keeps all of them together under that. An account can have 50 imports queued or running at once. Status endpoints allow 3,600 requests per hour per job type; a check every 20 seconds is 180 an hour for each job in progress, so about 20 jobs can be checked at once, which is why the check worker runs with `concurrency: 20`. For hundreds of links, see [Batch imports](/docs/integrations/batch-imports.md).

`SOURCE_THROTTLED` and `LIVE_NOT_SUPPORTED` are the failure codes that can work on a later attempt (a site that is busy for now, or a stream that is still live). For those, add the start job again later; every other failure code is final. See [Media unavailable](/docs/errors/media-unavailable.md) and [Source throttled](/docs/errors/source-throttled.md).

Prefer a webhook? Start the job with a `webhookUrl` and save the result in an Express route, as in [Webhooks](/docs/webhooks.md#verify-signatures). Each job gets one delivery and no retries, so keep `importly-check` as a fallback for jobs that stay pending.

A `youtube.com/playlist?list=…` link is rejected with `PLAYLIST_NOT_SUPPORTED`. Add one job per video instead.

> [!NOTE]
>
> A transcript from captions costs $0.003, speech-to-text is $0.01 per minute, and a download is billed by size, about \$0.15 for a 10-minute 720p video. `maxCostDollars` caps what one link can cost. Try it free, no card required. See [Pricing & credits](/docs/billing.md).


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