> ## 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 Trigger.dev tasks

> Transcribe or download any video or audio link from a Trigger.dev task: the webhook completes a waitpoint token, so the run pauses while the job works and resumes with the result.

If your app hands video or podcast links to [Trigger.dev](https://trigger.dev) tasks, the media step is the one that breaks once it runs in the cloud: sites block the datacenter IPs the task runs on, and many videos have no captions to read. Call Importly from the task 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.

Imports can take a few minutes for long videos. Rather than polling, the task passes a Trigger.dev [waitpoint token](https://trigger.dev/docs/wait-for-token) URL as Importly's `webhookUrl`. The run pauses until Importly posts the result to that URL, and you aren't billed for compute while it waits.

This page uses `@trigger.dev/sdk` v4 and plain `fetch`.

## 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` in your Trigger.dev project's environment variables for each environment you deploy to, and to `.env` for `trigger dev`:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
```

## 2. A small client

Both tasks share one helper that sends a request and turns an error response into an exception. A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) won't change on a retry, so they abort the run. Anything else throws a normal error, and Trigger.dev retries the run with the task's `retry` settings:

```ts trigger/importly.ts theme={null}
import { AbortTaskRunError } from '@trigger.dev/sdk'

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

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

  const message = `Importly ${res.status} ${json.code ?? ''}: ${json.error ?? 'request failed'}`
  if ([400, 401, 402].includes(res.status)) throw new AbortTaskRunError(message)
  throw new Error(message) // 429 and 5xx: let Trigger.dev retry the run
}

// What Importly posts to the webhook URL when a job finishes
export type ImportlyWebhook<T> = {
  success: boolean
  data: T & { jobId: string, type: string, status: 'completed' | 'failed', code?: string, message?: string }
}

// Failures that can work on a later attempt; every other code is final
export const RETRY_LATER = new Set(['SOURCE_THROTTLED', 'LIVE_NOT_SUPPORTED'])
```

## 3. Transcribe a link

`"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 in the response. When it doesn't, the run waits on the token until the webhook arrives:

```ts trigger/transcribe-link.ts theme={null}
import { AbortTaskRunError, logger, task, wait } from '@trigger.dev/sdk'
import { importly, RETRY_LATER, type ImportlyWebhook } from './importly'

type Transcript = {
  text: string
  source: string
  language?: string
  duration?: number
  data?: { segments: { start: number, end: number, text: string }[] }
  costInDollars?: number
}

type TranscribeJob = { jobId: string, status: string, result?: Transcript, code?: string, message?: string }

export const transcribeLink = task({
  id: 'transcribe-link',
  retry: { maxAttempts: 3 },
  run: async (payload: { url: string }) => {
    const token = await wait.createToken({ timeout: '30m' })

    const job = await importly<TranscribeJob>('/transcribe', {
      method: 'POST',
      body: { url: payload.url, mode: 'auto', wait: true, maxCostDollars: 1, webhookUrl: token.url },
    })
    if (job.status === 'completed' && job.result) return job.result

    logger.info('Transcript still running, waiting for the webhook', { jobId: job.jobId })
    const result = await wait.forToken<ImportlyWebhook<Transcript>>(token)

    // The token timed out (a missed webhook): read the job once from the API
    const done = result.ok
      ? result.output.data
      : await importly<TranscribeJob>(`/transcribe/status?id=${encodeURIComponent(job.jobId)}`)

    if (done.status !== 'completed') {
      const message = `${done.code}: ${done.message}`
      if (done.code && RETRY_LATER.has(done.code)) throw new Error(message)
      throw new AbortTaskRunError(message)
    }
    return 'result' in done && done.result ? done.result : (done as Transcript)
  },
})
```

The webhook payload has the transcript fields directly on `data`, while the status endpoint nests them under `result` ([Webhooks](/docs/webhooks.md#payload-shape)), which is why the last line handles both. A caption transcript costs \$0.003; speech-to-text is billed per minute, and `maxCostDollars` caps what one link can cost. More options are in [Transcripts](/docs/features/transcripts.md).

## 4. Download the file

`POST /import` returns a job ID straight away, and the file is ready when the webhook arrives:

```ts trigger/import-link.ts theme={null}
import { AbortTaskRunError, task, wait } from '@trigger.dev/sdk'
import { importly, RETRY_LATER, type ImportlyWebhook } from './importly'

type ImportResult = { mediaUrl: string, title: string, duration?: number, filename?: string, costInDollars?: number }
type ImportJob = { jobId: string, status: string, result?: ImportResult, code?: string, message?: string }

export const importLink = task({
  id: 'import-link',
  retry: { maxAttempts: 3 },
  run: async (payload: { url: string, audioOnly?: boolean }) => {
    const token = await wait.createToken({ timeout: '1h' })

    const { jobId } = await importly<ImportJob>('/import', {
      method: 'POST',
      body: {
        url: payload.url,
        includeVideo: !payload.audioOnly,
        videoQuality: '720p', // a ceiling: lower if the source has no 720p
        maxCostDollars: 0.5, // the most this one file may cost
        webhookUrl: token.url,
      },
    })

    const result = await wait.forToken<ImportlyWebhook<ImportResult>>(token)
    const job = result.ok
      ? { ...result.output.data, result: result.output.data }
      : await importly<ImportJob>(`/import/status?id=${encodeURIComponent(jobId)}`)

    if (job.status === 'completed' && job.result) {
      // mediaUrl is a signed link that expires after 7 days: copy the file now if you keep it
      return job.result
    }
    if (job.status === 'queued' || job.status === 'running') {
      throw new Error(`Import ${jobId} still ${job.status} after the wait`)
    }

    const message = `${job.code}: ${job.message}`
    if (job.code && RETRY_LATER.has(job.code)) throw new Error(message)
    throw new AbortTaskRunError(message) // MAX_COST_EXCEEDED, VIDEO_PRIVATE, VIDEO_UNAVAILABLE, …
  },
})
```

`mediaUrl` is valid for 7 days. To keep files, copy them to your storage in the next step of the task, or connect your bucket once and import with `store: true` so every file lands there ([Save to your bucket](/docs/integrations/save-to-bucket.md)).

## Run it

Start `npx trigger.dev@latest dev`, open the task in the dashboard and run it with:

```json theme={null}
{ "url": "https://www.youtube.com/watch?v=jNQXAC9IVRw" }
```

Or trigger it from your app's backend:

```ts theme={null}
import { tasks } from '@trigger.dev/sdk'
import type { transcribeLink } from '@/trigger/transcribe-link'

await tasks.trigger<typeof transcribeLink>('transcribe-link', { url })
```

## Notes

`POST /import` allows 240 requests per hour per key, and an account can have 50 imports queued or running at once. A `429` throws a normal error, so Trigger.dev retries the run later. For hundreds of links, set a [queue](https://trigger.dev/docs/queue-concurrency) with a `concurrencyLimit` on the import task, and see [Batch imports](/docs/integrations/batch-imports.md).

Running your own Node workers on Redis instead of Trigger.dev? The [BullMQ guide](/docs/integrations/bullmq.md) does the same job with two queues and one shared rate limit.

Importly posts each result once, with no retries. The token's `timeout` is the fallback: when it passes, the task reads the job from the status endpoint instead.

A `youtube.com/playlist?list=…` link is rejected with `PLAYLIST_NOT_SUPPORTED`. Trigger one run per video, for example with `batchTrigger`.


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