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

# Download an X (Twitter) video in Node

> Node.js code that takes an X or Twitter post link, gets the MP4 through the Importly API and saves it to disk, with polling, error handling and the response you get back.

Your users paste an X post and your Node backend needs the video file. Without an X developer account there's no stable way to get it from a server: page scraping and unofficial endpoints break, and requests from cloud IPs get blocked or rate-limited. This sends the post link to Importly and saves the finished MP4. It runs on Node 18 or later with no dependencies.

## The code

```js download-x-video.mjs theme={null}
import { writeFile } from 'node:fs/promises'

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

export async function downloadXVideo(postUrl, outputPath) {
  // 1. Start the import. It returns a jobId right away.
  const start = await fetch(`${API}/import`, {
    method: 'POST',
    headers,
    // videoQuality is a ceiling; maxCostDollars caps what one link can cost
    body: JSON.stringify({ url: postUrl, videoQuality: '720p', maxCostDollars: 0.25 }),
  })
  const started = await start.json()
  if (!start.ok || !started.success) {
    // Rejected up front: bad link, bad key, low balance or rate limit
    throw new Error(`${started.code}: ${started.error}`)
  }

  // 2. Poll until the job is done.
  let job
  do {
    await sleep(3000)
    const res = await fetch(`${API}/import/status?id=${started.data.jobId}`, { headers })
    job = (await res.json()).data
  } while (job.status === 'queued' || job.status === 'running')

  if (job.status === 'failed') {
    // e.g. VIDEO_UNAVAILABLE or AUTH_REQUIRED. Failed imports aren't charged.
    throw new Error(`${job.code}: ${job.message}`)
  }

  // 3. Save the file. mediaUrl is a signed link, valid for 7 days.
  const file = await fetch(job.result.mediaUrl)
  await writeFile(outputPath, Buffer.from(await file.arrayBuffer()))
  return job.result
}

const result = await downloadXVideo(process.argv[2], 'x-video.mp4')
console.log(`Saved "${result.title}" (${result.duration}s) for $${result.totalCostInDollars}`)
```

```bash theme={null}
IMPORTLY_API_KEY=your_api_key node download-x-video.mjs "https://x.com/<user>/status/<id>"
```

Send the link as your users paste it: `x.com` and `twitter.com` post links both work, with or without tracking parameters.

## What comes back

The finished job from `GET /import/status`:

```json theme={null}
{
  "success": true,
  "data": {
    "jobId": "a824760e-ece1-4415-8838-ce2a7785ea6b",
    "status": "completed",
    "result": {
      "mediaUrl": "https://storage.example.com/imports/a824760e-…/video.mp4?X-Amz-…",
      "title": "Example post text",
      "duration": 41,
      "fileSizeBytes": 6291456,
      "costInDollars": 0.012,
      "totalCostInDollars": 0.012
    }
  }
}
```

X serves each video in several bitrates. You don't pick one: Importly takes the best stream at or below `videoQuality` and gives you a single MP4. Set `includeVideo: false` for the audio only, or add `includeTranscript: true` for a timestamped transcript in the same job. All options are in [Downloads](/docs/features/downloads.md).

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `400` `INVALID_URL` | Show the user the link isn't an X post |
| 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"` | The post was deleted; tell the user |
| Status | `status: "failed"`, `code: "AUTH_REQUIRED"` or `"VIDEO_PRIVATE"` | Protected account or a post that needs a login; tell the user |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | The video costs more than `maxCostDollars`; raise the cap or lower `videoQuality` |

Importly fetches what's public. Every error has a `documentationUrl` with the fix. See [Media unavailable](/docs/errors/media-unavailable.md) and [Error handling](/docs/error-handling.md). Only download videos your users have the right to use.

## Check a post before you download

Users often paste posts that have only text or images, and those imports fail. `POST /metadata/basic` returns the title and duration for \$0.003, so you can confirm there's a video, and how long it is, before you start an import. See [Metadata](/docs/features/metadata.md).

## In production

* Don't make a web request wait on the loop above. Pass `webhookUrl` and save the file when Importly calls you back ([Webhooks](/docs/webhooks.md)), and keep a status check as a fallback.
* Copy the file somewhere permanent, or set `store: true` to have every import land in your own bucket ([recipe](/docs/integrations/save-to-bucket.md)).
* For many links at once, see [Batch imports](/docs/integrations/batch-imports.md).

> [!NOTE]
>
> Downloads cost $0.002 per MB, with a $0.01 minimum, so a one-minute clip at 720p is usually two to four cents. 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.