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

# See a video's download options and cost before importing, in Node

> List every quality a video link can be downloaded at, each with its file type, size and price, then import the one you pick - so you (or your agent) spend only after seeing the cost.

Before you download a video link, you often want to know what you'll get and what it will cost: which resolutions are available, whether the file plays everywhere, and the price of each. Importly's [`POST /metadata`](/docs/endpoints/metadata) returns that list for any link, so you can show a user the choices, or let an agent pick, and only then import the one you want. A metadata call is \$0.003 and never downloads the media; you pay the download price only when you call [`POST /import`](/docs/features/downloads). The same recipe in Python is [Options and cost in Python](/docs/recipes/pick-quality-and-cost-python.md).

## The code

```js options.mjs theme={null}
const API = 'https://api.importly.io'
const headers = {
  Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
  'Content-Type': 'application/json',
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

// Run any job to completion: POST to start, then poll its status endpoint.
const runJob = async (path, body, statusPath) => {
  const start = await fetch(`${API}${path}`, { method: 'POST', headers, body: JSON.stringify(body) })
  const started = await start.json()
  if (!start.ok || !started.success) throw new Error(`${started.code}: ${started.error}`)

  let job = started.data
  for (let i = 0; i < 120 && (job.status === 'queued' || job.status === 'running'); i++) {
    await sleep(2000) // up to ~4 min; pass a webhookUrl instead in a queue worker
    const res = await fetch(`${API}${statusPath}?id=${job.jobId}`, { headers })
    job = (await res.json()).data
  }
  if (job.status !== 'completed') throw new Error(job.message || `Job ${job.status}`)
  return job.result
}

// List the download options for a link, cheapest first.
const getDownloadOptions = async (url) => {
  const meta = await runJob('/metadata', { url }, '/metadata/status')
  const { downloadOptions } = meta
  if (!downloadOptions) return { title: meta.title, video: [], audio: [] } // e.g. a live stream
  return { title: meta.title, video: downloadOptions.video, audio: downloadOptions.audio }
}

// Download one chosen quality and return a link to the file.
const importQuality = async (url, videoQuality) => {
  const result = await runJob('/import', { url, videoQuality }, '/import/status')
  return { mediaUrl: result.mediaUrl, cost: result.totalCostInDollars, filename: result.filename }
}

const url = 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
const { title, video } = await getDownloadOptions(url)

console.log(title)
for (const o of video) {
  const cost = o.estimatedCost == null ? 'size unknown' : `$${o.estimatedCost.toFixed(2)}`
  const playsEverywhere = o.h264 ? '' : ' (re-encode for Safari/iOS with compatibleCodecs)'
  console.log(`  ${o.videoQuality.padEnd(6)} ${o.ext}  ${o.width}x${o.height}  ${cost}${playsEverywhere}`)
}

// Pick the cheapest option at 720p or below, then import it.
const choice = video
  .filter((o) => o.height <= 720 && o.estimatedCost != null)
  .sort((a, b) => a.estimatedCost - b.estimatedCost)[0]
if (choice) {
  const file = await importQuality(url, choice.videoQuality)
  console.log(`Imported ${file.filename} for $${file.cost}: ${file.mediaUrl}`)
}
```

```bash theme={null}
IMPORTLY_API_KEY=your_api_key node options.mjs
```

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.

## What comes back

The finished metadata job has a `downloadOptions` object with a `video` list and an `audio` list. Each row is one file you could import:

```json theme={null}
"downloadOptions": {
  "video": [
    { "videoQuality": "144p", "alsoMatches": ["lowest"], "width": 192, "height": 144, "fps": 15, "ext": "mp4", "h264": false, "estimatedBytes": 499526, "estimatedCost": 0.01 },
    { "videoQuality": "240p", "alsoMatches": ["360p", "480p", "720p", "1080p", "1440p", "2160p", "best"], "default": true, "width": 320, "height": 240, "ext": "mp4", "h264": false, "estimatedBytes": 538398, "estimatedCost": 0.01 }
  ],
  "audio": [
    { "audioQuality": "medium", "alsoMatches": ["high", "best"], "default": true, "bitrateKbps": 106, "estimatedBytes": 252182, "estimatedCost": 0.01 }
  ]
}
```

* Send a row's `videoQuality` to [`POST /import`](/docs/features/downloads) to get that file, or its `audioQuality` with `includeVideo: false` for audio only.
* `estimatedCost` is the price you'd pay for that import, in dollars. It's `null` when the source gives no size, so guard for it before sorting or displaying.
* Rows that return the same file are folded into one: the others are listed in `alsoMatches`, and `default: true` marks what you get if you import without naming a quality. So a video that tops out at 1080p lists it once with `1440p`, `2160p` and `best` beside it.
* `h264: false` means the file won't play in Safari, on iOS or in QuickTime as is. Send `compatibleCodecs: true` with the import to get an H.264 version where the source has one (usually a larger file, so the cost goes up).
* `video` is empty for audio-only sources such as podcasts, and `downloadOptions` is absent for a live stream that hasn't ended.

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `400` with an `error` | Not a valid link, or a playlist page (`PLAYLIST_NOT_SUPPORTED`). Ask for a single video link |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Add credits; nothing was charged |
| Start request | HTTP `429` | Wait `retryAfter` seconds and retry |
| Status | `status: "failed"`, e.g. `VIDEO_UNAVAILABLE` or `VIDEO_PRIVATE` | The video is gone or private; nothing was charged |

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

> [!NOTE]
>
> Listing the options costs \$0.003 per link, and status checks are free. You pay the download price only when you import. 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.