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

# Download an Instagram reel in Node

> Node.js code that takes a public Instagram reel link, gets the MP4 through the Importly API and saves it, with polling, error handling and the response you get back.

Your users paste an Instagram reel link and your Node backend needs the video. Instagram's own API only covers accounts that connect to your app, and anonymous requests from servers hit a login wall. This sends the public reel link to Importly and saves the finished MP4. It runs on Node 18 or later with no dependencies. The [Python version](/docs/recipes/instagram-reel-python.md) does the same with `requests`.

## The code

```js download-reel.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 downloadReel(reelUrl, outputPath) {
  // 1. Start the import. It returns a jobId right away.
  const start = await fetch(`${API}/import`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ url: reelUrl }),
  })
  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_PRIVATE 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)
  if (!file.ok) throw new Error(`Download failed: HTTP ${file.status}`)
  await writeFile(outputPath, Buffer.from(await file.arrayBuffer()))
  return job.result
}

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

```bash theme={null}
IMPORTLY_API_KEY=your_api_key node download-reel.mjs "https://www.instagram.com/reel/<id>/"
```

`/reel/` and `/p/` links both work, with or without the `?igsh=…` share parameter, 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-…/reel.mp4?X-Amz-…",
      "title": "Video by example_account",
      "duration": 22,
      "fileSizeBytes": 3104512,
      "costInDollars": 0.01,
      "totalCostInDollars": 0.01
    }
  }
}
```

Set `includeVideo: false` in the request body 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 reel |
| 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 `"AUTH_REQUIRED"` | The reel is private or needs a login; tell the user |

Importly fetches what's public: private accounts, close-friends stories and anything behind a login fail and aren't charged. Only download reels your users have the right to use. See [Supported sites](/docs/features/supported-sites.md) and [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.
* On serverless hosts with short time limits, start the import in one function and handle the webhook in another. See [Vercel function limits](/docs/integrations/vercel-function-limits.md) for the pattern.
* Copy the file somewhere permanent, or set `store: true` to have it land in your own bucket ([recipe](/docs/integrations/save-to-bucket.md)).

> [!NOTE]
>
> Downloads cost $0.002 per MB, with a $0.01 minimum, so a minute-long reel is usually a few 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.