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

# Show a preview for any video link in Node

> An Express route that turns a pasted video link into a preview card: title, thumbnail, length and whether it's live, with polling, caching and the errors to handle.

When a user pastes a video link into your app, you usually want a preview before anything else: the title, a thumbnail and how long it is. Scraping that yourself means a different parser per site, and from a server many sites answer with a bot check instead of the page. This route sends the link to Importly's [basic metadata](/docs/features/metadata.md) endpoint and returns a small preview object. It runs on Node 18 or later with Express.

## The code

```js preview.mjs theme={null}
import express from 'express'

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))

// The same link always gives the same preview, so look each one up once
const cache = new Map()

const getPreview = async (url) => {
  if (cache.has(url)) return cache.get(url)

  // 1. Start the lookup. It returns a jobId right away.
  const start = await fetch(`${API}/metadata/basic`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ url }),
  })
  const started = await start.json()
  if (!start.ok || !started.success) {
    // Rejected up front (not charged): not a valid link, a playlist, a bad key or a low balance
    return { error: started.error, code: started.code, httpStatus: start.status }
  }

  // 2. Poll the status endpoint (free) until the job is done, for up to 30 seconds
  let job = started.data
  for (let i = 0; i < 20 && (job.status === 'queued' || job.status === 'running'); i++) {
    await sleep(1500)
    const res = await fetch(`${API}/metadata/basic/status?id=${job.jobId}`, { headers })
    job = (await res.json()).data
  }

  if (job.status === 'failed') {
    // e.g. VIDEO_UNAVAILABLE or VIDEO_PRIVATE. Failed lookups aren't charged.
    return { error: job.message, code: job.code, httpStatus: 422 }
  }
  if (job.status !== 'completed') {
    return { error: 'Still looking this link up, try again in a moment', httpStatus: 202 }
  }

  const { title, duration, thumbnail, isLive } = job.result
  const preview = { url, title, duration, thumbnail, isLive }
  cache.set(url, preview)
  return preview
}

const app = express()
app.use(express.json())

app.post('/api/preview', async (req, res) => {
  const { url } = req.body ?? {}
  if (typeof url !== 'string' || !url) return res.status(400).json({ error: 'Send a url' })

  const { httpStatus = 200, ...preview } = await getPreview(url.trim())
  res.status(httpStatus).json(preview)
})

app.listen(3000, () => console.log('Listening on http://localhost:3000'))
```

```bash theme={null}
npm install express
IMPORTLY_API_KEY=your_api_key node preview.mjs

curl -X POST http://localhost:3000/api/preview \
  -H "Content-Type: application/json" \
  -d '{"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"}'
```

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. The browser only calls your `/api/preview` route.

## What comes back

The finished job from `GET /metadata/basic/status` has four fields under `result`:

```json theme={null}
{
  "success": true,
  "data": {
    "jobId": "56380f26-3895-487a-8551-bc2a8b9c63ba",
    "status": "completed",
    "result": {
      "title": "Me at the zoo",
      "duration": 19,
      "thumbnail": "https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg",
      "isLive": false
    }
  }
}
```

`duration` is in seconds. A live stream that hasn't ended has `isLive: true` and `duration: null`, so show a "Live" badge instead of a length. It can't be downloaded or transcribed until the stream ends.

For the description, uploader, upload date or view counts, call [`POST /metadata`](/docs/endpoints/metadata) instead. It costs the same and returns everything the source exposes.

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `400` with an `error` message | 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"`, `code: "VIDEO_UNAVAILABLE"` or `"VIDEO_PRIVATE"` | The video is gone or private; show that on the card |

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

## In production

* Swap the `Map` for your database or Redis, keyed by the link, so a preview is looked up once across restarts and servers.
* If you store the thumbnail, copy the image to your own storage. Some platforms sign their image links, and those stop working after a while.
* Use `duration` to check a video before a bigger job: reject anything over your length limit before you pay to [download](/docs/features/downloads.md) or [transcribe](/docs/features/transcripts.md) it.
* Saving previews in the background (a feed, an import queue)? Pass a `webhookUrl` and save the result when Importly calls you back. See [Webhooks](/docs/webhooks.md).

> [!NOTE]
>
> A preview costs \$0.003 per link, 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.