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

# Transcribe new podcast episodes from an RSS feed in Node

> A Node.js script you run on a schedule: it reads a podcast's RSS feed, sends each new episode to speech-to-text with a cost cap, and stores the transcript and timestamps in SQLite, once per episode.

Podcast audio has no captions, so a podcast app that shows transcripts, writes show notes or searches inside episodes needs speech-to-text on every new episode. Doing that yourself means fetching each audio file, keeping a speech-to-text account, and tracking which episodes are done. This Node script reads the show's RSS feed, sends each new episode's audio link to Importly's [transcripts](/docs/features/transcripts.md) endpoint, and saves the text and timestamped segments in SQLite. Run it from cron, a scheduled worker or a platform's cron job: each run collects the transcripts that finished and starts the episodes that are new. The same script in Python is [Podcast feed transcripts in Python](/docs/recipes/podcast-rss-transcripts-python.md).

## The code

```js transcribe-feed.mjs theme={null}
import Database from 'better-sqlite3'
import { XMLParser } from 'fast-xml-parser'

const API = 'https://api.importly.io'
const FEED_URL = process.argv[2]
const MAX_COST = Number(process.env.MAX_COST_PER_EPISODE ?? '1.50') // 150 minutes at $0.01/min
const MAX_NEW_PER_RUN = 10

const headers = {
  Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
  'Content-Type': 'application/json',
}

const db = new Database('episodes.db')
db.exec(`
  create table if not exists episodes (
    guid text primary key,
    title text,
    audio_url text,
    job_id text,
    status text,
    transcript text,
    segments text,
    cost real,
    error text
  )
`)

// <guid> and <title> can be plain text or carry attributes
const text = (value) => (value && typeof value === 'object' ? value['#text'] : value)

// The episode's audio file, from the RSS <enclosure>
function audioUrl(item) {
  const enclosures = [item.enclosure ?? []].flat()
  return enclosures.find((e) => e['@_type']?.startsWith('audio/'))?.['@_url'] ?? null
}

async function startNewEpisodes() {
  const res = await fetch(FEED_URL)
  if (!res.ok) throw new Error(`Feed returned ${res.status}`)
  const parser = new XMLParser({ ignoreAttributes: false, isArray: (name) => name === 'item' })
  const items = parser.parse(await res.text()).rss?.channel?.item ?? []

  const seen = db.prepare(`select 1 from episodes where guid = ?`)
  const insert = db.prepare(
    `insert into episodes (guid, title, audio_url, job_id, status, error) values (?, ?, ?, ?, ?, ?)`
  )
  let started = 0
  for (const item of items) {
    const guid = String(text(item.guid) ?? item.link ?? '')
    const url = audioUrl(item)
    const title = String(text(item.title) ?? '')
    if (!guid || !url) continue
    if (seen.get(guid)) continue // already started or done
    if (started >= MAX_NEW_PER_RUN) break

    const res = await fetch(`${API}/transcribe`, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        url,
        mode: 'ai', // podcast audio has no captions
        maxCostDollars: MAX_COST, // the most one episode may cost
        language: 'en',
      }),
    })
    const body = await res.json()
    if (res.status === 402 || res.status === 429) {
      // Out of credits, or the hourly or in-progress limit: try the rest next run
      console.log(`Stopping for this run: ${body.code} ${body.error}`)
      return
    }
    if (!res.ok || !body.success) {
      // A link Importly can't take. Record it so it isn't sent again.
      insert.run(guid, title, url, null, 'failed', body.error ?? null)
      continue
    }
    insert.run(guid, title, url, body.data.jobId, body.data.status, null)
    started += 1
    console.log(`Started: ${title}`)
  }
}

async function collectFinished() {
  const pending = db
    .prepare(`select guid, job_id from episodes where status in ('queued', 'running')`)
    .all()
  for (const { guid, job_id: jobId } of pending) {
    const res = await fetch(`${API}/transcribe/status?id=${jobId}`, { headers })
    const { data } = await res.json()
    if (data.status === 'completed') {
      const { result } = data
      db.prepare(
        `update episodes set status = 'completed', transcript = ?, segments = ?, cost = ? where guid = ?`
      ).run(result.text, JSON.stringify(result.data.segments), result.costInDollars, guid)
    } else if (data.status === 'failed') {
      // e.g. MAX_COST_EXCEEDED for an episode longer than your cap. Not charged.
      db.prepare(`update episodes set status = 'failed', error = ? where guid = ?`)
        .run(`${data.code}: ${data.message}`, guid)
    }
  }
}

await collectFinished()
await startNewEpisodes()
```

```bash theme={null}
npm install better-sqlite3 fast-xml-parser
export IMPORTLY_API_KEY=your_api_key

# Run it every 15 minutes with the show's feed URL (Node 18 or later)
node transcribe-feed.mjs https://example.com/your-show/feed.xml
```

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and keep it on the server.

## How it works

The audio link comes from the feed. Each RSS `<item>` has an `<enclosure>` with the episode's audio file in its `url` attribute. Importly takes direct media links like these, as well as episode pages on [supported sites](/docs/features/supported-sites.md). The parser keeps attributes (`ignoreAttributes: false`), so the enclosure's `url` and `type` come through as `@_url` and `@_type`.

`mode: 'ai'` goes straight to speech-to-text. Podcast audio has no captions, so there's nothing to check first. For a feed of videos that might have captions, send `mode: 'auto'` instead: captions cost \$0.003 and speech-to-text only runs when there are none.

`maxCostDollars` caps each episode. Speech-to-text is $0.01 per minute, so the default of $1.50 covers episodes up to 150 minutes. A longer episode fails with `MAX_COST_EXCEEDED` and isn't charged. When the length isn't known up front, the cap is held while the episode is transcribed and the unused part is refunded.

Each episode is sent once. The episode's `<guid>` is the key in SQLite, so a re-run skips everything already started, finished or failed. Unfinished jobs are picked up by the next run, so no run sits waiting on a long episode. Feeds list the newest episode first, so the first run starts the 10 newest and the back catalog follows 10 per run.

Set `language` to the show's language (a two-letter code like `es`). Without it, speech-to-text transcribes as English.

## What gets stored

A finished job from `GET /transcribe/status` has the transcript under `result`. The script stores `text`, the `segments` as JSON, and `costInDollars`:

```json theme={null}
{
  "text": "Welcome back to the show...",
  "source": "importly",
  "language": "en",
  "duration": 1834,
  "data": {
    "segments": [
      { "start": 0.4, "end": 3.1, "text": "Welcome back to the show." }
    ]
  },
  "costInDollars": 0.31
}
```

Segment times are in seconds, one segment per sentence, so you can link a search hit or a quote to the moment it was said.

## Errors to handle

| Where | What you see | What the script does |
| - | - | - |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Stops starting episodes until the next run. Add credits; nothing was charged |
| Start request | HTTP `429` `RATE_LIMITED` | Stops until the next run. You hit the hourly limit or have 50 transcriptions queued or running. See [Rate limits](/docs/error-handling.md#rate-limits) |
| Start request | HTTP `400` | Records the episode as failed so it isn't sent again. Usually a link that isn't a media file or page |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | Records it. Raise `MAX_COST_PER_EPISODE` and delete the row to retry |
| Status | `status: "failed"` with another `code` | Records it. The audio link is gone or can't be fetched. Failed transcriptions are refunded |

Every error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.md).

## In production

Use a webhook instead of polling. Pass a `webhookUrl` when you start each episode and save the transcript when Importly calls you back. Keep the status check as a fallback. See [Webhooks](/docs/webhooks.md).

Running on a host without a persistent disk (serverless functions, most container platforms)? `episodes.db` is gone on the next deploy. Keep the same table in your app's Postgres or another database; the queries don't change. To hand each episode to a queue worker instead, see [BullMQ](/docs/integrations/bullmq.md).

Many feeds? Loop over them in the same run. `MAX_NEW_PER_RUN` keeps a back catalog from starting hundreds of jobs at once, and a `429` just moves the rest to the next run.

Want the audio file too? Send the episode to [`POST /import`](/docs/endpoints/import) with `includeTranscript: true` and `transcriptProvider: 'importly'` and you get the file in your bucket and the transcript from one job. See [Save to your bucket](/docs/integrations/save-to-bucket.md).

Your own speech-to-text key? Add `provider: 'deepgram'` (or `assemblyai`, `openai`) and `apiKey` to pay \$0.005 per minute plus your provider's fees.

An app that transcribes around the clock shouldn't stop when credit runs out. Turn on [auto top-up](/docs/billing.md#auto-top-up), or watch for the [low-balance emails](/docs/billing.md#low-balance-emails).

> [!NOTE]
>
> A 30-minute episode costs \$0.30 with Importly speech-to-text, and status checks are free. 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.