> ## 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 a link to Supabase Storage (Lovable, Bolt)

> A tested recipe for Lovable, Bolt and other Supabase apps: a user pastes a TikTok, YouTube or X link, the video file lands in your own Supabase Storage bucket, a table records it, and the frontend plays it with a signed URL.

Your Lovable or Bolt app needs a "paste a video link" feature: a user adds a TikTok, YouTube or X link and the video shows up in their library. The download code an app builder writes usually works in the preview and then gets blocked once it runs on a server, and an Edge Function can't run a downloader anyway. With Importly, the Edge Function sends the link and the file lands in your own Supabase Storage bucket, next to the rest of your app's data.

What you build:

* `start-import`, an Edge Function the signed-in user calls with a link. It starts the import and adds a row to a `videos` table.
* `importly-webhook`, a second function that Importly calls when the file is in your bucket. It checks the signature and marks the row ready.
* A frontend list that shows each user their own videos with signed URLs, so the bucket stays private.

Every step below was tested against a real Supabase project, with a TikTok link imported into a private bucket.

## 1. Connect your bucket once

Create a private bucket (this guide calls it `imports`) and an S3 access key in your Supabase project, then save them on the dashboard's [S3 Storage](https://www.importly.io/dashboard/s3-storage) page and click **Test connection**. The steps and the exact field values are in [Supabase Storage setup](/docs/s3-storage.md#supabase-storage).

Supabase's S3 access keys can read and write every bucket in the project. Paste them into Importly only, never into your app's code or a prompt.

On the Supabase Free plan, a single file can be at most 50 MB, and a 10-minute 720p video is about 77 MB. A file over your project's limit doesn't reach the bucket: the import still completes, and the result has `s3StorageError` instead of `s3Storage`. Use a lower `videoQuality`, audio only (`includeVideo: false`), or raise the limit on a paid plan. See Supabase's [file limits](https://supabase.com/docs/guides/storage/uploads/file-limits).

## 2. Add your Importly keys as secrets

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once), and copy the **Webhook signing secret** (it starts with `whsec_`) from the same page. Store both as Edge Function secrets, in the Supabase dashboard under **Edge Functions > Secrets**, or with the CLI:

```bash theme={null}
supabase secrets set IMPORTLY_API_KEY=your_api_key IMPORTLY_WEBHOOK_SECRET=whsec_your_secret
```

`SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` are already available inside every Edge Function.

## 3. The table and the Storage policy

Run this in the SQL editor. Users can read their own rows, and only the functions write them. The second policy lets a signed-in user create signed URLs for files under `users/<their id>/`, which is where `start-import` puts them.

```sql theme={null}
create table public.videos (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  source_url text not null,
  job_id text not null unique,
  status text not null default 'queued',
  title text,
  storage_key text,
  error_message text,
  created_at timestamptz not null default now()
);

alter table public.videos enable row level security;

create policy "Users read their own videos"
  on public.videos for select to authenticated
  using ((select auth.uid()) = user_id);

create policy "Users read their own imported files"
  on storage.objects for select to authenticated
  using (
    bucket_id = 'imports'
    and (storage.foldername(name))[1] = 'users'
    and (storage.foldername(name))[2] = (select auth.uid())::text
  );
```

## 4. Start the import

The frontend calls this function with the user's session. `store: true` sends the file to your bucket, `storagePath` puts it in the user's folder, and `storageFilename` gives it a short, predictable name (without it, the file is named after the video's title, spaces and emoji included).

```ts supabase/functions/start-import/index.ts theme={null}
import { createClient } from 'npm:@supabase/supabase-js@2'

const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!)

Deno.serve(async (req) => {
  const token = req.headers.get('Authorization')?.replace('Bearer ', '') ?? ''
  const { data: { user } } = await supabase.auth.getUser(token)
  if (!user) return Response.json({ error: 'Sign in first' }, { status: 401 })

  const { url } = await req.json()
  // the file name in the bucket, so keys stay short and predictable
  const fileId = crypto.randomUUID()

  const res = await fetch('https://api.importly.io/import', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${Deno.env.get('IMPORTLY_API_KEY')}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url,
      store: true,
      storagePath: `users/${user.id}`,
      storageFilename: fileId,
      videoQuality: '720p',
      // H.264 where the source has it, so the file plays in every browser
      compatibleCodecs: true,
      // links come from users, so cap what one import can cost
      maxCostDollars: 0.5,
      webhookUrl: `${Deno.env.get('SUPABASE_URL')}/functions/v1/importly-webhook`,
    }),
  })
  const body = await res.json()
  if (!body.success) return Response.json({ error: body.error, code: body.code }, { status: res.status })

  const { data, error } = await supabase
    .from('videos')
    .insert({ user_id: user.id, source_url: url, job_id: body.data.jobId })
    .select('id, status')
    .single()
  if (error) return Response.json({ error: error.message }, { status: 500 })

  return Response.json(data)
})
```

A rejected request comes back with Importly's status, `error` and `code`, and no row is written. A wrong `IMPORTLY_API_KEY` secret, for example, gives a 401 with `UNAUTHORIZED`. See [Error handling](/docs/error-handling.md).

`compatibleCodecs` gets H.264 video wherever the source has it at that size. TikTok only has H.264 up to 540p, so a 720p TikTok import comes back as HEVC, which some browsers can't play. Use `videoQuality: '480p'` if every file has to play everywhere. Each result reports its `videoCodec`. See [Codecs](/docs/features/downloads.md#codecs).

## 5. Mark the row ready from the webhook

Importly sends one signed `POST` when the job finishes. Importly can't send a Supabase JWT, so turn off the JWT check for this function. The signature check is what keeps other callers out.

```toml supabase/config.toml theme={null}
[functions.importly-webhook]
verify_jwt = false
```

The payload has the file's place in your bucket under `s3Storage.key`. Once the signature checks out, the function saves that key on the row:

```ts supabase/functions/importly-webhook/index.ts theme={null}
import { createClient } from 'npm:@supabase/supabase-js@2'

const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!)

const hexToBytes = (hex: string) => {
  if (!/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) return null
  return new Uint8Array(hex.match(/../g)!.map((byte) => parseInt(byte, 16)))
}

const verifyImportlySignature = async (header: string | null, rawBody: string, secret: string, toleranceSeconds = 300) => {
  if (!header) return false
  const parts = header.split(',').map((part) => part.trim().split('='))
  const timestamp = Number(parts.find(([key]) => key === 't')?.[1])
  if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false

  const encoder = new TextEncoder()
  const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'])
  const signed = encoder.encode(`${timestamp}.${rawBody}`)

  for (const [name, value] of parts) {
    const signature = name === 'v1' ? hexToBytes(value ?? '') : null
    if (signature && (await crypto.subtle.verify('HMAC', key, signature, signed))) return true
  }
  return false
}

Deno.serve(async (req) => {
  // the raw text: the signature covers the exact bytes Importly sent
  const rawBody = await req.text()
  const secret = Deno.env.get('IMPORTLY_WEBHOOK_SECRET') ?? ''
  if (!secret || !(await verifyImportlySignature(req.headers.get('Importly-Signature'), rawBody, secret))) {
    return new Response(null, { status: 400 })
  }

  const { success, data } = JSON.parse(rawBody)
  if (data?.type !== 'import' || typeof data.jobId !== 'string') return new Response(null, { status: 200 })

  const update = !success
    ? { status: 'failed', error_message: data.message ?? null }
    : data.s3Storage
      ? { status: 'ready', title: data.title ?? null, storage_key: data.s3Storage.key }
      : { status: 'failed', error_message: data.s3StorageError ?? 'The file was not saved to Storage' }

  await supabase.from('videos').update(update).eq('job_id', data.jobId).eq('status', 'queued')
  return new Response(null, { status: 200 })
})
```

A request without a valid signature gets a 400 and changes nothing. The `status = 'queued'` filter makes a repeated delivery harmless. If the download worked but the copy to your bucket didn't (a revoked S3 key, say), the payload has `s3StorageError` instead of `s3Storage`, and the row records why. See [When the copy fails](/docs/integrations/save-to-bucket.md#when-the-copy-fails).

Deploy both functions:

```bash theme={null}
supabase functions deploy start-import
supabase functions deploy importly-webhook --no-verify-jwt
```

## 6. Show each user their videos

The frontend starts an import with `supabase.functions.invoke`, which sends the user's session for you, and lists the ready rows with signed URLs. RLS returns only the user's own rows, and the Storage policy lets them sign only their own files.

```tsx src/components/VideoLibrary.tsx theme={null}
import { useEffect, useState } from 'react'
import { supabase } from '@/integrations/supabase/client'

type Video = { id: string; title: string | null; signedUrl: string }

export const VideoLibrary = () => {
  const [videos, setVideos] = useState<Video[]>([])
  const [link, setLink] = useState('')

  const load = async () => {
    const { data: rows } = await supabase
      .from('videos')
      .select('id, title, storage_key')
      .eq('status', 'ready')
      .order('created_at', { ascending: false })
    if (!rows?.length) return setVideos([])

    const { data: signed } = await supabase.storage
      .from('imports')
      .createSignedUrls(rows.map((row) => row.storage_key), 3600)
    setVideos(rows.map((row, i) => ({ id: row.id, title: row.title, signedUrl: signed?.[i]?.signedUrl ?? '' })))
  }

  const addVideo = async () => {
    const { error } = await supabase.functions.invoke('start-import', { body: { url: link } })
    if (error) return alert(error.message)
    setLink('')
  }

  useEffect(() => {
    load()
    // refresh when the webhook marks a row ready
    const channel = supabase
      .channel('videos')
      .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'videos' }, load)
      .subscribe()
    return () => {
      supabase.removeChannel(channel)
    }
  }, [])

  return (
    <div>
      <input value={link} onChange={(e) => setLink(e.target.value)} placeholder="Paste a video link" />
      <button onClick={addVideo}>Add video</button>
      {videos.map((video) => (
        <figure key={video.id}>
          <video src={video.signedUrl} controls width={320} />
          <figcaption>{video.title}</figcaption>
        </figure>
      ))}
    </div>
  )
}
```

For live updates, turn on Realtime for the `videos` table (**Database > Publications**, or `alter publication supabase_realtime add table public.videos`). Without it, call `load()` again after a few seconds. The import path is the one Lovable uses; in Bolt or your own setup, import your Supabase client from wherever it lives.

## 7. Or let the builder write it

Paste this into Lovable or Bolt after step 1, and it builds the same feature:

Video library in Supabase Storage

Add a video library. A signed-in user pastes a video link; a Supabase Edge Function "start-import" sends it to POST [https://api.importly.io/import](https://api.importly.io/import) with store: true, storagePath "users/USER\_ID", storageFilename set to a new UUID, videoQuality "720p", compatibleCodecs: true, maxCostDollars: 0.5 and webhookUrl pointing at a second function "importly-webhook". Read the key from the IMPORTLY\_API\_KEY secret, never from client code. Save each job in a "videos" table (user\_id, source\_url, job\_id, status, title, storage\_key) with RLS so users read only their own rows. "importly-webhook" runs with verify\_jwt off, checks the Importly-Signature header with the IMPORTLY\_WEBHOOK\_SECRET secret, and saves data.s3Storage.key on the row. Files are in the private "imports" bucket; show them with createSignedUrls, with a Storage policy that lets users sign files under users/their-id/. Follow [https://www.importly.io/docs/integrations/supabase-storage](https://www.importly.io/docs/integrations/supabase-storage)

The builder will ask you to add the two secrets from step 2.

## Catch a missed webhook

Each job gets one webhook delivery and no retries, and a function served on `localhost` never receives it. For rows still `queued` after a few minutes, read the job with [`GET /import/status`](/docs/endpoints/import-status) and save `result.s3Storage.key` the same way. The [Supabase Edge Functions recipe](/docs/integrations/supabase-edge-functions.md#6-catch-missed-webhooks) has a sweep function you can adapt, run every few minutes with Supabase Cron.

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

For transcripts instead of files, see [Save transcripts to Supabase from an Edge Function](/docs/integrations/supabase-edge-functions.md). For other app builders and the MCP connector, see [Lovable, Bolt & Replit](/docs/integrations/app-builders.md).


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