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

# Download a TikTok video in Node

> Node.js code that takes a TikTok 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 a TikTok link and your Node backend needs the video file. Fetching TikTok yourself works on a laptop and gets blocked from servers, so this sends the link to Importly and saves the finished MP4. It runs on Node 18 or later with no dependencies.

## The code

```js download-tiktok.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 downloadTikTok(tiktokUrl, outputPath) {
  // 1. Start the import. It returns a jobId right away.
  const start = await fetch(`${API}/import`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ url: tiktokUrl, videoQuality: '720p' }),
  })
  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 (a short TikTok usually takes a few seconds).
  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_PRIVATE or VIDEO_UNAVAILABLE. 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 downloadTikTok(process.argv[2], 'tiktok.mp4')
console.log(`Saved "${result.title}" (${result.duration}s) for $${result.totalCostInDollars}`)
```

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

Share links such as `vm.tiktok.com/...` work as they are, so you can pass on whatever your users paste.

## 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 TikTok caption",
      "duration": 14,
      "fileSizeBytes": 1837204,
      "costInDollars": 0.01,
      "totalCostInDollars": 0.01
    }
  }
}
```

TikTok videos are portrait, so `720p` means 720 pixels on the short side (720×1280). Set `includeVideo: false` for the audio only. 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 a video |
| 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_PRIVATE"` or `"VIDEO_UNAVAILABLE"` | The video is private or gone; tell the user |

Every error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.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 short TikTok is usually about a cent. 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.