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

# Save videos from links into Replit App Storage

> A Replit app that saves videos from pasted TikTok, YouTube or X links: why the download fails once the app is published, the free fix for direct file links, and a tested Express backend that copies each video into private App Storage and serves it to your users.

You asked Replit Agent for an app where users paste a video link and the video gets saved. It works in the workspace preview with a test clip. Published, the save fails: the "video" is an HTML page, the site answers `403` or a bot check, or the request hangs until it times out. Files the app wrote to disk are gone after a restart.

* A TikTok, YouTube, Instagram or X link is a web page, not a file, so `fetch` gets HTML back.
* Many sites block requests from cloud servers, so a download that works from your laptop fails from the published app.
* Autoscale deployments scale to zero when idle and [restart regularly by design](https://docs.replit.com/help/deployment-and-publishing), so a file written to the deployment's disk isn't kept. Files belong in [App Storage](https://docs.replit.com/features/data-and-storage/object-storage).

This page shows the free fix for links that already point at a file, where it stops, and a tested backend that gets any supported link into App Storage.

## How App Storage works

From Replit's [App Storage](https://docs.replit.com/features/data-and-storage/object-storage) and [JavaScript SDK](https://docs.replit.com/features/sdks/object-storage-javascript-sdk) pages, checked November 27, 2026:

* Buckets are always private. There is no public URL, so your app serves files to the users it has authorized.
* Your app reaches its bucket through Replit's SDK (`@replit/object-storage` for JavaScript, also one for Python), with no access keys to manage.
* The app can upload, download, list and delete objects, but not change bucket settings.
* There are no lifecycle rules. To clean up old files, run a Scheduled deployment that deletes them.

Because App Storage has no S3 access keys, Importly's `store: true` delivery doesn't apply here. Your backend copies the finished file into the bucket itself, server to server, as shown below.

## Free fix for direct file links

If the link points straight at a file (an `.mp4` on a CDN or in another bucket), don't read it into memory or write it to disk. Stream it into App Storage:

```ts theme={null}
import { Readable } from 'node:stream'
import type { ReadableStream } from 'node:stream/web'
import { Client } from '@replit/object-storage'

const storage = new Client()

export const saveFileFromUrl = async (fileUrl: string, key: string) => {
  const res = await fetch(fileUrl)
  if (!res.ok || !res.body) throw new Error(`Source returned ${res.status}`)
  await storage.uploadFromStream(key, Readable.fromWeb(res.body as ReadableStream))
}
```

`uploadFromStream` resolves when the upload finishes and throws if it fails.

## Where the free fix stops

Users rarely paste a file URL. They paste the page they watched the video on:

* Getting the video out of a TikTok, YouTube or X page takes a downloader, and keeping one working means updating it every time a site changes.
* The published app runs on datacenter IPs, which many sites block, so the downloader that works in the preview gets errors in production.
* Long videos keep the request open the whole time, with the user waiting on it.

## Send the link, copy the finished file

With Importly, your backend only sends the link. Importly downloads the video and calls your webhook when the file is ready, then your webhook copies it into App Storage. The tested Express server below has three routes:

1. `POST /api/videos` starts the import and returns at once.
2. `POST /api/webhooks/importly` copies the finished file into App Storage.
3. `GET /api/videos/:jobId/file` streams the file back to your users from the private bucket.

Add your Importly API key in the Secrets tool as `IMPORTLY_API_KEY`, and your published app's URL (for example `https://your-app.replit.app`) as `APP_URL`. Install the SDK with `npm install @replit/object-storage`, and create a bucket in the App Storage tool. `new Client()` uses the app's default bucket.

```ts server/index.ts theme={null}
import express from 'express'
import { Readable } from 'node:stream'
import type { ReadableStream } from 'node:stream/web'
import { Client } from '@replit/object-storage'

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

const storage = new Client() // the bucket you created in the App Storage tool
const importlyHeaders = { Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}` }

// 1. The user pastes a link: start the import and return straight away
app.post('/api/videos', async (req, res) => {
  const response = await fetch('https://api.importly.io/import', {
    method: 'POST',
    headers: { ...importlyHeaders, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      url: req.body.url, // the TikTok, YouTube or X link the user pasted
      videoQuality: '720p',
      maxCostDollars: 0.5,
      webhookUrl: `${process.env.APP_URL}/api/webhooks/importly`,
    }),
  })
  const body = await response.json()
  if (!response.ok || !body.success) {
    return res.status(response.status).json({ error: body.error, code: body.code })
  }

  // save body.data.jobId on the user's video record, with status 'pending'
  res.json({ jobId: body.data.jobId, status: body.data.status })
})

// 2. Importly calls back when the file is ready: copy it into App Storage
const saveFile = async (jobId: string) => {
  const response = await fetch(`https://api.importly.io/import/status?id=${encodeURIComponent(jobId)}`, {
    headers: importlyHeaders,
  })
  const body = await response.json()
  if (!body.success) return

  const job = body.data
  if (job.status === 'failed') {
    // mark the record failed with job.code and job.message
    return
  }
  if (job.status !== 'completed') return

  const extension = job.result.filename.split('.').pop()
  const key = `videos/${jobId}.${extension}`
  const already = await storage.exists(key)
  if (already.ok && already.value) return // a retried webhook for a file you already copied

  // server to server: from Importly's storage straight into your bucket, no temp file
  const file = await fetch(job.result.mediaUrl)
  if (!file.ok || !file.body) throw new Error(`Download returned ${file.status}`)
  await storage.uploadFromStream(key, Readable.fromWeb(file.body as ReadableStream))
  // find the record by jobId and save key, job.result.title and job.result.duration
}

app.post('/api/webhooks/importly', async (req, res) => {
  const { data } = req.body ?? {}
  if (data?.type !== 'import' || typeof data.jobId !== 'string') return res.sendStatus(200)
  try {
    await saveFile(data.jobId)
    res.sendStatus(200)
  } catch (error) {
    console.error('Copy to App Storage failed', data.jobId, error)
    res.sendStatus(500) // Importly retries the delivery later
  }
})

// 3. Your users get the file through your app (buckets are private)
app.get('/api/videos/:jobId/file', (req, res) => {
  // check the signed-in user owns this video, and read its key from the record
  const key = `videos/${req.params.jobId}.mp4`
  storage
    .downloadAsStream(key)
    .on('error', () => res.status(404).end())
    .pipe(res.type('video/mp4'))
})

app.listen(Number(process.env.PORT ?? 5000), '0.0.0.0')
```

A few notes on the webhook route:

* It takes only the `jobId` from the request and reads the result from the API with your key, so a forged request can't put a file into your bucket. To reject forged requests earlier, also check the `Importly-Signature` header as shown in [Verify signatures](/docs/webhooks.md#verify-signatures).
* It answers `200` after the copy, and `500` if the copy fails. Importly waits 10 seconds for an answer and [retries](/docs/webhooks.md#retries) a delivery that fails or times out, with the same `Importly-Webhook-Id`. A long video can take longer than 10 seconds to copy, so a retry may arrive for a file that's already saved; the `exists` check skips it.
* The retries back off to hours apart, so also check records that have been pending for a few minutes with [`GET /import/status`](/docs/endpoints/import-status) and run the same `saveFile`. The webhook URL must be public, so while you work in the workspace, poll the status endpoint instead.

`mediaUrl` stays valid for 7 days, so the copy can also run later from a status check. Set `includeVideo: false` for audio only. For a transcript instead of the file, see [Use Importly from Lovable, Bolt or Replit](/docs/integrations/app-builders.md); there's no file to move.

We ran this server against the live API with a TikTok link: the webhook copied the 1.5 MB video in under a second, a repeated delivery was skipped, and the file route returned the same bytes. App Storage itself was replaced by a local stand-in for the test, since it only runs on Replit.

> [!NOTE]
>
> A 10-minute 720p video costs about \$0.15 to import, and `maxCostDollars` stops a long one before it's charged. 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.