> ## 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 Express without a job queue

> Transcribe or download any video or audio link from an Express app with no Redis or worker: start the job from a route, save the result from a signed webhook, and catch missed ones with a cron script.

If your Express backend takes video or podcast links, the download or transcript 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 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.

You don't need Redis or a worker for this. A route starts the Importly job and stores its ID, Importly sends a signed webhook to your app when the job finishes, and a small script run from cron picks up any job whose webhook didn't arrive. If you already run BullMQ, see [BullMQ](/docs/integrations/bullmq.md) instead. The code uses Node 18+ `fetch`, Express and Postgres through `pg`.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once). On the same page, under **Webhook signing secret**, click **Reveal** and copy the `whsec_…` secret. Add both to your server's environment, and to `.env` for development:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
IMPORTLY_WEBHOOK_SECRET=whsec_your_secret
SITE_URL=https://your-app.example
DATABASE_URL=postgres://localhost/myapp
```

```bash theme={null}
npm install express pg
```

The code saves to a `videos` table:

```sql theme={null}
create table videos (
  id bigserial primary key,
  url text not null,
  importly_job_id text,
  importly_kind text not null, -- 'transcribe' or 'import'
  importly_status text, -- queued, running, completed, failed
  importly_result jsonb,
  importly_error text,
  created_at timestamptz not null default now()
);
create index on videos (importly_job_id);
```

## 2. A small client

A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) throws with the API's message. A webhook's result fields sit in `data` itself, while the status endpoint nests them under `result`, so `saveResult` takes the job and its result separately:

```js importly.js theme={null}
import pg from 'pg'

export const db = new pg.Pool({ connectionString: process.env.DATABASE_URL })

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

export const call = async (path, body) => {
  const res = await fetch(`https://api.importly.io${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
  throw new Error(`Importly ${res.status} ${data.code ?? ''}: ${data.error ?? 'request failed'}`)
}

export const saveResult = async (videoId, job, result) => {
  // a transcript has result.text; an import has result.mediaUrl, valid for 7 days
  await db.query(
    `update videos set importly_status = $2, importly_result = $3, importly_error = $4 where id = $1`,
    [
      videoId,
      job.status,
      job.status === 'completed' ? result : null,
      job.status === 'failed' ? `${job.code}: ${job.message}` : null,
    ],
  )
}
```

## 3. Start the job from a route

`"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 this one call and is saved straight away. Anything still `queued` or `running` finishes later through the webhook. `maxCostDollars` caps what one link can cost:

```js app.js theme={null}
import crypto from 'node:crypto'
import express from 'express'
import { call, db, saveResult } from './importly.js'

const app = express()
const webhookUrl = `${process.env.SITE_URL}/webhooks/importly`

app.post('/videos', express.json(), async (req, res) => {
  const { rows } = await db.query(
    `insert into videos (url, importly_kind) values ($1, 'transcribe') returning id`,
    [req.body.url],
  )
  const videoId = rows[0].id
  try {
    const job = await call('/transcribe', {
      url: req.body.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,
      webhookUrl,
    })
    await db.query('update videos set importly_job_id = $2 where id = $1', [videoId, job.jobId])
    await saveResult(videoId, job, job.result)
    res.json({ id: videoId, status: job.status })
  } catch (error) {
    await db.query(`update videos set importly_status = 'failed', importly_error = $2 where id = $1`, [videoId, error.message])
    res.status(400).json({ id: videoId, error: error.message })
  }
})
```

To download the file instead, insert the row with `importly_kind` `'import'` and call `POST /import`. It returns a job ID straight away, and the webhook brings the `mediaUrl`:

```js theme={null}
const job = await call('/import', {
  url: req.body.url,
  includeVideo: true, // false for audio only
  videoQuality: '720p', // a ceiling: lower if the source has no 720p
  maxCostDollars: 0.5, // the most this one file may cost
  webhookUrl,
})
```

`webhookUrl` must be a public `https://` address. In local development, leave it out and run the script in step 5 to fetch results.

## 4. The webhook route

Importly sends one `POST` when the job finishes. Check the `Importly-Signature` header against the raw body before you trust it, so use `express.raw` on this route, not `express.json`: parsing the JSON first changes the bytes and the signature won't match.

```js app.js theme={null}
const verifyImportlySignature = (header, rawBody, secret, toleranceSeconds = 300) => {
  if (!header) return false
  const parts = header.split(',').map((part) => part.trim().split('='))
  const timestamp = Number(parts.find(([key]) => key === 't')?.[1])
  const signatures = parts.filter(([key]) => key === 'v1').map(([, value]) => value)
  if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false
  const expected = crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')
  return signatures.some((signature) =>
    signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)))
}

app.post('/webhooks/importly', express.raw({ type: 'application/json' }), async (req, res) => {
  const rawBody = req.body.toString('utf8')
  if (!verifyImportlySignature(req.get('Importly-Signature'), rawBody, process.env.IMPORTLY_WEBHOOK_SECRET)) {
    return res.sendStatus(400)
  }
  const { data = {} } = JSON.parse(rawBody)
  // skip unknown jobs, and jobs the script in step 5 already finished
  const { rows } = await db.query(
    `select id from videos where importly_job_id = $1 and importly_status not in ('completed', 'failed')`,
    [data.jobId],
  )
  if (rows[0]) await saveResult(rows[0].id, data, data) // a webhook's result fields are in data itself
  res.sendStatus(200)
})

app.listen(process.env.PORT ?? 3000)
```

A finished transcript's `importly_result` has `text`, and `data.segments` with `start` and `end` times in seconds. A finished import's has `mediaUrl`, a link to the file that's valid for 7 days: copy it 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)). See [Webhooks](/docs/webhooks.md) for every payload.

## 5. Catch missed webhooks

Each job gets one webhook delivery and no retries, so a deploy or a brief outage can miss one. This script asks the status endpoint about every job that has been pending for more than two minutes, and gives up on jobs still pending after an hour:

```js check-importly-jobs.js theme={null}
import { STATUS_PATH, call, db, saveResult } from './importly.js'

const { rows } = await db.query(
  `select id, importly_kind, importly_job_id, created_at < now() - interval '1 hour' as is_stale
   from videos
   where importly_status in ('queued', 'running') and importly_job_id is not null
     and created_at < now() - interval '2 minutes'
   limit 100`,
)
for (const video of rows) {
  try {
    const job = await call(`${STATUS_PATH[video.importly_kind]}?id=${encodeURIComponent(video.importly_job_id)}`)
    if (job.status === 'completed' || job.status === 'failed') {
      await saveResult(video.id, job, job.result)
    } else if (video.is_stale) {
      await saveResult(video.id, { status: 'failed', code: 'TIMEOUT', message: `still ${job.status} after an hour` })
    }
  } catch (error) {
    console.error(`video ${video.id}: ${error.message}`)
  }
}
await db.end()
```

Run it every few minutes from cron, or from your platform's scheduler (Render cron jobs, Railway cron, Heroku Scheduler, a Kubernetes CronJob):

```bash crontab theme={null}
*/5 * * * * cd /srv/app && node check-importly-jobs.js
```

## Notes

A caption transcript costs \$0.003; speech-to-text is billed per minute, and downloads by size. See [Transcripts](/docs/features/transcripts.md), [Downloads](/docs/features/downloads.md) and [Pricing](/docs/billing.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, start the 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).

`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`. Insert one row per video instead.


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