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

# Save downloaded videos to your own bucket

> A backend recipe in TypeScript: connect your S3, R2, B2 or Spaces bucket once, then every import your app starts lands in it, with a webhook that records where the file went.

This recipe is for apps that keep the files: a clip library, a media archive, an editor that works on the user's uploads. Your backend sends a link to Importly, and the video or audio file arrives in your own bucket under a key you choose. Importly's own download link expires after 7 days; the copy in your bucket is yours to keep.

The code is plain TypeScript with `fetch`, so it runs in a Next.js route handler, an Express or Hono server, or a queue worker. Keep `IMPORTLY_API_KEY` on the server: create it on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once).

## 1. Connect your bucket once

Create a bucket and an upload-only key first (the steps for S3, R2, B2 and Spaces are in [Deliver to your bucket](/docs/s3-storage.md)). Then save the settings, either on the dashboard's [S3 Storage](https://www.importly.io/dashboard/s3-storage) page or with one API call from a setup script:

```ts scripts/connect-bucket.ts theme={null}
const res = await fetch('https://api.importly.io/s3-storage', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    accessKeyId: process.env.BUCKET_ACCESS_KEY_ID,
    secretAccessKey: process.env.BUCKET_SECRET_ACCESS_KEY,
    bucketName: 'my-app-media',
    region: 'auto', // the bucket's region; `auto` for Cloudflare R2
    endpoint: 'https://ACCOUNT_ID.r2.cloudflarestorage.com', // leave out for Amazon S3
    defaultPathPrefix: 'imports',
  }),
})

const body = await res.json()
if (!res.ok || !body.success) throw new Error(`Bucket not saved: ${body.error}`)
console.log(body.message) // "S3 storage configuration saved successfully"
```

Saving tests the connection first: it uploads a small `importly-test-<timestamp>.txt` to the root of the bucket, and nothing is saved if that upload fails. To check credentials without saving them, send the same body to [`POST /s3-storage/test`](/docs/endpoints/test-s3-storage).

This is a one-time step per Importly account, not per import. All your app's imports go to this bucket unless a request names another one with `storageBucket`.

## 2. Start an import into the bucket

When a user adds a link, start the import with `store: true` and a `storagePath` that keeps your bucket organised. Save the `jobId` on your own record so the webhook can find it:

```ts lib/importly.ts theme={null}
type StartImport = {
  url: string
  userId: string
  audioOnly?: boolean
}

export const startImport = async ({ url, userId, audioOnly = false }: StartImport) => {
  const res = await fetch('https://api.importly.io/import', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url,
      store: true,
      storagePath: `users/${userId}`,
      includeVideo: !audioOnly,
      videoQuality: '1080p', // a ceiling: lower if the source has no 1080p
      maxCostDollars: 1, // links come from users, so cap what one import can cost
      webhookUrl: `${process.env.APP_URL}/api/webhooks/importly`,
    }),
  })

  const body = await res.json()
  if (!res.ok || !body.success) {
    // a bad link, a key problem or a low balance: show body.error to the user
    throw new Error(body.error ?? `Import not started (${res.status})`)
  }

  return body.data.jobId as string
}
```

The file is named after the media title unless you set `storageFilename` (no extension; Importly adds it). See [Downloads](/docs/features/downloads.md) for qualities, audio formats and transcripts in the same request.

## 3. Record where the file went

Importly sends one `POST` to `webhookUrl` when the job finishes or fails. This handler takes only the `jobId` from it and reads the result from the API with your key, so a forged request can't put data into your app. Every delivery is also signed: to reject forged requests before calling the API, check the `Importly-Signature` header as shown in [Verify signatures](/docs/webhooks.md#verify-signatures). It's a Next.js route handler here; in another framework, the body is the same.

```ts app/api/webhooks/importly/route.ts theme={null}
export async function POST(request: Request) {
  const { data } = await request.json()
  if (data?.type !== 'import' || typeof data.jobId !== 'string') return new Response(null, { status: 200 })

  const res = await fetch(`https://api.importly.io/import/status?id=${encodeURIComponent(data.jobId)}`, {
    headers: { Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}` },
    cache: 'no-store',
  })
  const body = await res.json()
  if (!body.success) return new Response(null, { status: 200 })

  const job = body.data
  if (job.status === 'failed') {
    // find your record by job.jobId and mark it failed with job.code and job.message
    return new Response(null, { status: 200 })
  }
  if (job.status !== 'completed') return new Response(null, { status: 200 })

  const { s3Storage, s3StorageError, mediaUrl, title, duration, totalCostInDollars } = job.result
  if (s3Storage) {
    // the file is in your bucket: save s3Storage.bucket and s3Storage.key on the record
  } else {
    // the import worked but the copy didn't: s3StorageError says why,
    // and mediaUrl still has the file for 7 days, so you can retry the copy yourself
  }

  return new Response(null, { status: 200 })
}
```

`s3Storage` has the object's `bucket`, `key` and full `url`. Store the key rather than the URL: buckets are private by default, so you'll usually serve the file through presigned URLs or a CDN in front of the bucket.

Each job gets one webhook delivery and no retries, so also check imports that have been pending for a few minutes with [`GET /import/status`](/docs/endpoints/import-status). The webhook URL must be public `https://`; in local development, poll the status endpoint instead. See [Webhooks](/docs/webhooks.md).

## When the copy fails

A failed copy never fails the import. The job completes, you're charged for the download as usual, and the result has `s3StorageError` instead of `s3Storage`. The usual reasons:

* No bucket saved: `store: true` on an account with no storage set up (or with storage turned off) gives an `s3StorageError` that starts with `No S3 storage is set up for this account`. Run step 1.
* Credentials or permissions changed: a rotated key, or a bucket policy that no longer allows `s3:PutObject`. Save the new key with step 1.
* A storage class the region doesn't support: leave `storageClass` out, or pick one the bucket's region offers.

More in the [S3 storage troubleshooting](/docs/s3-storage.md#troubleshooting) section.

> [!NOTE]
>
> Downloads cost $0.002 per MB, with a $0.01 minimum per import: a 10-minute 720p video is about \$0.15. Copying it to your bucket costs nothing extra. Try it free, no card required. See [Pricing & credits](/docs/billing.md).

## Let your agent write it

Using Claude Code or Cursor on this app? Connect the [MCP server](/docs/integrations/mcp.md) and ask it to save imports to your bucket with Importly. It reads the same docs, writes the route and the webhook for your stack, and can test with a real link first. See [Build with your agent](/docs/integrations/build-with-your-agent.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.