> ## 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 Inngest functions

> Transcribe or download any video or audio link from an Inngest function, with durable steps that start the job, sleep and check until the result is ready.

If your app sends video or podcast links to [Inngest](https://www.inngest.com) functions, the media step 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 a step 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. The functions below start the job in one step, then `step.sleep` and check the job's status until it's done. A sleeping function isn't running, and each check is its own step, so a retry never starts the job twice.

This page uses the `inngest` v3 SDK 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` to the environment where your app serves Inngest functions, and to `.env` for local development:

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

## 2. A small client

Both functions share one helper. A `429` throws a `RetryAfterError` with the `retryAfter` the API sent, so Inngest retries the step after that wait. A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) won't change on a retry, so they throw a `NonRetriableError`. Anything else is a normal error, and Inngest retries the step:

```ts inngest/importly.ts theme={null}
import { NonRetriableError, RetryAfterError } from 'inngest'

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

export const importly = async <T>(path: string, body?: unknown) => {
  const res = await fetch(`${API}${path}`, {
    method: body === undefined ? 'GET' : 'POST',
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: body === undefined ? undefined : JSON.stringify(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 (res.status === 429) throw new RetryAfterError(message, (json.retryAfter ?? 60) * 1000)
  if ([400, 401, 402].includes(res.status)) throw new NonRetriableError(message)
  throw new Error(message) // 5xx: Inngest retries the step
}

export type Job<R> = { jobId: string, status: string, result?: R, code?: string, message?: string }

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

export const failJob = (job: { code?: string, message?: string }): never => {
  const message = `${job.code}: ${job.message}`
  if (job.code && RETRY_LATER.has(job.code)) throw new Error(message)
  throw new NonRetriableError(message)
}
```

```ts inngest/client.ts theme={null}
import { Inngest } from 'inngest'

export const inngest = new Inngest({ id: 'my-app' })
```

## 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 from the first step. Otherwise the function sleeps and checks:

```ts inngest/transcribe-link.ts theme={null}
import { inngest } from './client'
import { failJob, importly, type Job } from './importly'

type Transcript = {
  text: string
  source: string
  language?: string
  duration?: number
  costInDollars?: number
}

export const transcribeLink = inngest.createFunction(
  { id: 'transcribe-link', retries: 3 },
  { event: 'app/link.transcribe' },
  async ({ event, step }) => {
    // Captions usually come back within the 30-second wait
    let job = await step.run('start-transcript', () =>
      importly<Job<Transcript>>('/transcribe', {
        url: event.data.url,
        mode: 'auto', // captions, or speech-to-text when there are none
        wait: true,
        maxCostDollars: 1,
      }),
    )

    // Speech-to-text on a long file takes longer: check every 20 seconds, for up to an hour
    for (let check = 1; check <= 180 && (job.status === 'queued' || job.status === 'running'); check++) {
      await step.sleep(`wait-${check}`, '20s')
      job = await step.run(`check-${check}`, () =>
        importly<Job<Transcript>>(`/transcribe/status?id=${encodeURIComponent(job.jobId)}`),
      )
    }

    if (job.status === 'completed' && job.result) return job.result
    if (job.status !== 'failed') throw new Error(`Transcript ${job.jobId} still ${job.status}`)
    return failJob(job)
  },
)
```

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. The `concurrency` limit keeps at most 10 imports in progress from this function:

```ts inngest/import-link.ts theme={null}
import { inngest } from './client'
import { failJob, importly, type Job } from './importly'

type ImportResult = { mediaUrl: string, title: string, duration?: number, filename?: string, costInDollars?: number }

export const importLink = inngest.createFunction(
  { id: 'import-link', retries: 3, concurrency: { limit: 10 } },
  { event: 'app/link.import' },
  async ({ event, step }) => {
    let job = await step.run('start-import', () =>
      importly<Job<ImportResult>>('/import', {
        url: event.data.url,
        includeVideo: !event.data.audioOnly,
        videoQuality: '720p', // a ceiling: lower if the source has no 720p
        maxCostDollars: 0.5, // the most this one file may cost
      }),
    )

    for (let check = 1; check <= 180 && (job.status === 'queued' || job.status === 'running'); check++) {
      await step.sleep(`wait-${check}`, '20s')
      job = await step.run(`check-${check}`, () =>
        importly<Job<ImportResult>>(`/import/status?id=${encodeURIComponent(job.jobId)}`),
      )
    }

    if (job.status === 'completed' && job.result) {
      // mediaUrl is a signed link that expires after 7 days: copy the file in a next step if you keep it
      return job.result
    }
    if (job.status !== 'failed') throw new Error(`Import ${job.jobId} still ${job.status}`)
    return failJob(job)
  },
)
```

`mediaUrl` is valid for 7 days. To keep files, copy them to your storage in a next step, 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

Add both functions to your `serve()` handler, start the Inngest dev server with `npx inngest-cli@latest dev`, and send an event from your app's backend:

```ts theme={null}
import { inngest } from '@/inngest/client'

await inngest.send({ name: 'app/link.transcribe', data: { url } })
```

## Notes

Why not a webhook? `step.waitForEvent` only sees events sent after the wait starts, and a short video can finish before that. Polling from durable steps avoids the race and needs no webhook setup. If you do route Importly's [webhook](/docs/webhooks.md) into Inngest, keep a status check after a `null` (timed-out) wait.

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 poll at once; the `concurrency` limit keeps you under that. `POST /import` allows 240 requests per hour per key, and an account can have 50 imports queued or running at once. For hundreds of links, see [Batch imports](/docs/integrations/batch-imports.md).

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


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