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

# Import each new video from a YouTube channel on a schedule in Node

> A Node.js script you run from cron or a scheduled worker: it reads a YouTube channel's public feed, imports each new upload once into your own bucket with its captions, caps the cost per video, and retries live streams after they end.

Apps that follow creators (a clip tool, a search index over a channel, an archive) need every new upload as a file soon after it's posted, with nobody pasting links. Importly takes one link per video and rejects channel and playlist pages, so the work is turning the channel into links and sending each one once. This Node script reads the channel's public feed, sends each new video to [`POST /import`](/docs/endpoints/import) with its captions, and keeps track in SQLite. Run it every 10 to 20 minutes from cron, a scheduled worker or a platform's cron job: each run saves the imports that finished, then starts the videos that are new. The same script in Python is [New channel videos in Python](/docs/recipes/youtube-channel-new-videos-python.md).

## The code

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

const API = 'https://api.importly.io'
const CHANNEL_ID = process.argv[2] // the UC... id from the channel page's URL or page source
const FEED_URL = `https://www.youtube.com/feeds/videos.xml?channel_id=${CHANNEL_ID}`
const MAX_COST = Number(process.env.MAX_COST_PER_VIDEO ?? '1.00') // about an hour of 720p
const SKIP_SHORTS = (process.env.SKIP_SHORTS ?? '1') === '1'
const MAX_NEW_PER_RUN = 5
const RETRY_LATER = { LIVE_NOT_SUPPORTED: 3600, SOURCE_THROTTLED: 300 } // code -> seconds to wait
const MAX_ATTEMPTS = 3

const headers = {
  Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
  'Content-Type': 'application/json',
}
const now = () => Date.now() / 1000

const db = new Database('channel.db')
db.exec(`
  create table if not exists videos (
    video_id text primary key,
    title text,
    url text,
    status text,          -- waiting, queued, running, completed, failed
    job_id text,
    attempts integer default 0,
    not_before real default 0,
    bucket_key text,
    media_url text,
    transcript text,
    cost real,
    error text
  )
`)

// Add each video in the feed that isn't in the table yet
async function addNewVideos() {
  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 === 'entry' })
  const feed = parser.parse(await res.text()).feed
  const insert = db.prepare(
    `insert or ignore into videos (video_id, title, url, status) values (?, ?, ?, 'waiting')`
  )
  for (const entry of feed.entry ?? []) {
    const videoId = entry['yt:videoId']
    if (!videoId) continue
    if (SKIP_SHORTS && entry.link?.['@_href']?.includes('/shorts/')) continue
    insert.run(videoId, String(entry.title), `https://www.youtube.com/watch?v=${videoId}`)
  }
}

async function startWaiting() {
  const rows = db
    .prepare(`select video_id, url from videos where status = 'waiting' and not_before <= ? limit ?`)
    .all(now(), MAX_NEW_PER_RUN)
  for (const { video_id: videoId, url } of rows) {
    const res = await fetch(`${API}/import`, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        url,
        videoQuality: '720p', // a ceiling: lower if the source has no 720p
        maxCostDollars: MAX_COST, // the most one video may cost, captions included
        includeTranscript: true, // the video's captions, $0.003
        store: true, // copy the file to your bucket
        storagePath: `youtube/${CHANNEL_ID}`,
        storageFilename: videoId,
      }),
    })
    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) {
      db.prepare(`update videos set status = 'failed', error = ? where video_id = ?`)
        .run(body.error ?? null, videoId)
    } else {
      db.prepare(`update videos set status = 'queued', job_id = ? where video_id = ?`)
        .run(body.data.jobId, videoId)
      console.log(`Started: ${videoId}`)
    }
  }
}

async function collectFinished() {
  const pending = db
    .prepare(`select video_id, job_id, attempts from videos where status in ('queued', 'running')`)
    .all()
  for (const { video_id: videoId, job_id: jobId, attempts } of pending) {
    const res = await fetch(`${API}/import/status?id=${jobId}`, { headers })
    const { data } = await res.json()
    if (data.status === 'completed') {
      const { result } = data
      db.prepare(
        `update videos set status = 'completed', bucket_key = ?, media_url = ?,
         transcript = ?, cost = ?, error = ? where video_id = ?`
      ).run(
        result.s3Storage?.key ?? null,
        result.mediaUrl, // expires after 7 days
        result.transcript?.text ?? null, // null when the video has no captions
        result.totalCostInDollars,
        result.s3StorageError ?? null, // set if the copy to your bucket failed
        videoId
      )
    } else if (data.status === 'failed') {
      const wait = RETRY_LATER[data.code]
      if (wait && attempts + 1 < MAX_ATTEMPTS) {
        // Still live, or the source asked us to slow down: send it again later
        db.prepare(
          `update videos set status = 'waiting', attempts = ?, not_before = ? where video_id = ?`
        ).run(attempts + 1, now() + wait, videoId)
      } else {
        db.prepare(`update videos set status = 'failed', error = ? where video_id = ?`)
          .run(`${data.code}: ${data.message}`, videoId)
      }
    } else {
      db.prepare(`update videos set status = ? where video_id = ?`).run(data.status, videoId)
    }
  }
}

await collectFinished()
await addNewVideos()
await startWaiting()
```

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

# Run it every 15 minutes with the channel's id (Node 18 or later)
node import-channel.mjs UC_x5XG1OV2P6uZZ5FSM9Ttw
```

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. Connect your bucket once before the first run: the steps for S3, R2, B2 and Spaces are in [Deliver to your bucket](/docs/s3-storage.md). Without a bucket, leave out `store` and the storage fields and copy each file from `mediaUrl` instead.

## How it works

The channel's feed is public and needs no YouTube API key. `https://www.youtube.com/feeds/videos.xml?channel_id=<id>` is an Atom feed of the channel's 15 most recent uploads, newest first. Each `<entry>` has a `<yt:videoId>`, a title and a publish time, and the script builds a plain watch URL from the id. As long as it runs more often than the channel posts 15 videos, nothing is missed.

Shorts are in the same feed, and their entry's link is a `/shorts/` URL. The script skips them by default; set `SKIP_SHORTS=0` to import them too. Importly takes [Shorts links](/docs/features/supported-sites.md) like any other video.

Each video is sent once. The video id is the primary key, so a re-run skips everything already started, finished or failed. A run never waits on a long download: imports still in progress are collected by the next run. The first run starts the 5 newest videos in the feed and the rest follow over the next two runs. To start from today instead, insert the current feed's ids as `completed` before the first run.

`maxCostDollars` caps each video. Downloads are $0.002 per MB, so a 10-minute 720p video is about $0.15, and the default of $1.00 covers about an hour of 720p. A longer video fails with `MAX_COST_EXCEEDED` before anything is downloaded and costs only $0.003 for the price check. Raise the cap, or send `includeVideo: false` for audio only, if the channel posts long streams.

`includeTranscript: true` adds the video's captions to the same job for $0.003. When a video has no captions, the import still succeeds and `transcript` is `{ "status": "skipped", "reason": "…" }`, so the script stores no text. To get speech-to-text for those, add `transcriptProvider: 'importly'` ($0.01 per minute). See [Transcripts inside an import](/docs/features/transcripts.md#transcripts-inside-an-import).

Live streams show up in the feed while they're live. They fail with `LIVE_NOT_SUPPORTED` and nothing is charged; the script sends them again an hour later, up to 3 tries.

## What gets stored

A finished job from `GET /import/status` has the file under `result`. The script stores the bucket key from `s3Storage`, the `mediaUrl`, the transcript `text` and `totalCostInDollars`:

```json theme={null}
{
  "mediaUrl": "https://…",
  "title": "My latest video",
  "duration": 612,
  "downloadedBytes": 79823104,
  "costInDollars": 0.154,
  "totalCostInDollars": 0.157,
  "transcript": { "text": "Hi everyone…", "source": "platform_captions", "language": "en" },
  "s3Storage": {
    "url": "https://my-app-media.s3.us-east-1.amazonaws.com/youtube/UC_x5XG1OV2P6uZZ5FSM9Ttw/WN5O4vWCa54.mp4",
    "bucket": "my-app-media",
    "key": "youtube/UC_x5XG1OV2P6uZZ5FSM9Ttw/WN5O4vWCa54.mp4"
  }
}
```

`mediaUrl` expires after 7 days; the copy in your bucket is yours to keep. If the copy to your bucket fails, the import still succeeds and `s3StorageError` says why. The script saves it in `error`.

## Errors to handle

| Where | What you see | What the script does |
| - | - | - |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Stops starting videos until the next run. Add credits; nothing was charged |
| Start request | HTTP `429` `RATE_LIMITED` | Stops until the next run. You hit 240 imports an hour or have 50 queued or running. See [Rate limits](/docs/error-handling.md#rate-limits) |
| Start request | HTTP `400` | Records the video as failed so it isn't sent again |
| Status | `status: "failed"`, `code: "LIVE_NOT_SUPPORTED"` | Sends it again in an hour, up to 3 tries |
| Status | `status: "failed"`, `code: "SOURCE_THROTTLED"` | Sends it again in 5 minutes, up to 3 tries. See [Source throttled](/docs/errors/source-throttled.md) |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | Records it. Raise `MAX_COST_PER_VIDEO` and set the row back to `waiting` to retry |
| Status | `status: "failed"` with another `code` | Records it. Private, deleted, age-restricted or members-only videos can't be imported. Failed imports aren't charged |

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 import and save the result when Importly calls you back. Keep the status check as a fallback: each job gets one delivery, with no retries. See [Webhooks](/docs/webhooks.md).

Running on a host without a persistent disk (serverless functions, most container platforms)? `channel.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 video to a queue worker instead, see [BullMQ](/docs/integrations/bullmq.md).

Many channels? Loop over their ids in the same run, with a `channel_id` column in the table. A `429` just moves the rest to the next run, and [Batch imports](/docs/integrations/batch-imports.md) shows a steady sender for larger volumes.

An app that imports 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 10-minute 720p video with its captions costs about \$0.16, 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.