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

# Show a preview for pasted video links in a Supabase app

> A tested Supabase recipe for Lovable, Bolt and other Supabase apps: when a user pastes a YouTube, TikTok or X link, an Edge Function returns its title, thumbnail and length, and a table keeps each preview so a link is only looked up once.

When someone pastes a video link into your app, the first thing to show is a preview card: the title, a thumbnail and how long it is. In a Lovable or Bolt app that usually starts as a fetch of the page from the browser, which most video sites block, or a scraper in an Edge Function that gets a bot check instead of the page once it runs on a server. Send the link to Importly's [basic metadata](/docs/features/metadata.md) endpoint instead, and keep the answer in a table.

This recipe is one Edge Function and one table:

* `link-preview` takes a link from a signed-in user, returns the preview from the `link_previews` table if anyone has pasted that link before, and otherwise looks it up and saves it.
* `link_previews` holds one row per link. Only the function reads and writes it, so it needs no policies.

Your frontend never sees your Importly key. For the same preview on a Node or Python server, see [Video link previews in Node](/docs/recipes/video-link-preview-node.md). To go on and save the video file or a transcript, see [Save videos to Supabase Storage](/docs/integrations/supabase-storage.md) and [Save transcripts to Supabase](/docs/integrations/supabase-edge-functions.md).

## 1. Add your key as a secret

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once) and store it as an Edge Function secret:

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

`SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` are already available inside every Edge Function. For `supabase functions serve`, put `IMPORTLY_API_KEY` in `supabase/functions/.env` and keep that file out of git.

## 2. The table

Run this in the SQL editor or add it as a migration. RLS is on with no policies, so the browser can't read or write it directly; the function uses the service role key.

```sql theme={null}
create table public.link_previews (
  url text primary key,
  title text,
  duration numeric,
  thumbnail text,
  is_live boolean,
  created_at timestamptz not null default now()
);

alter table public.link_previews enable row level security;
```

The same link always gives the same preview, so the link itself is the key. `duration` is `numeric` because some sites report fractions of a second.

## 3. The function

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

const API = 'https://api.importly.io'
const importlyHeaders = {
  Authorization: `Bearer ${Deno.env.get('IMPORTLY_API_KEY')}`,
  'Content-Type': 'application/json',
}
// The browser calls this function from your app's domain, so answer the CORS preflight
const cors = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}
const reply = (body: unknown, status = 200) => Response.json(body, { status, headers: cors })
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

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

Deno.serve(async (req) => {
  if (req.method === 'OPTIONS') return new Response('ok', { headers: cors })

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

  const { url } = await req.json().catch(() => ({}))
  if (typeof url !== 'string' || !url.trim()) return reply({ error: 'Send a url' }, 400)
  const link = url.trim()

  // 1. A link someone already previewed comes straight from the table, at no cost
  const { data: cached } = await supabase
    .from('link_previews')
    .select('url, title, duration, thumbnail, is_live')
    .eq('url', link)
    .maybeSingle()
  if (cached) return reply(cached)

  // 2. Start the lookup. It returns a jobId right away.
  const start = await fetch(`${API}/metadata/basic`, {
    method: 'POST',
    headers: importlyHeaders,
    body: JSON.stringify({ url: link }),
  })
  const started = await start.json()
  if (!started.success) {
    // Rejected up front, and not charged: not a valid link, a playlist, a bad key or a low balance
    return reply({ error: started.error, code: started.code }, start.status)
  }

  // 3. Poll the status endpoint (free) for up to 30 seconds
  let job = started.data
  for (let i = 0; i < 20 && (job.status === 'queued' || job.status === 'running'); i++) {
    await sleep(1500)
    const res = await fetch(`${API}/metadata/basic/status?id=${job.jobId}`, { headers: importlyHeaders })
    job = (await res.json()).data
  }
  if (job.status === 'failed') {
    // e.g. VIDEO_UNAVAILABLE or VIDEO_PRIVATE. Failed lookups aren't charged.
    return reply({ error: job.message, code: job.code }, 422)
  }
  if (job.status !== 'completed') return reply({ error: 'Still looking this link up, try again in a moment' }, 202)

  // 4. Save it, so the next person who pastes this link gets it from the table
  const { title, duration, thumbnail, isLive } = job.result
  const preview = { url: link, title, duration, thumbnail, is_live: isLive }
  const { error } = await supabase.from('link_previews').upsert(preview)
  if (error) return reply({ error: error.message }, 500)

  return reply(preview)
})
```

Deploy it with `supabase functions deploy link-preview`. Supabase checks the user's JWT before the function runs, and the `getUser` call makes sure it belongs to a real signed-in user, so people can't spend your credits from outside your app.

The function waits up to 30 seconds for a new link. Most previews come back in a few seconds, well inside the Edge Function limits (see [Edge Function limits](/docs/integrations/supabase-edge-function-limits.md)). A link already in the table comes back straight away.

## 4. Call it from your app

```ts theme={null}
const { data: preview, error } = await supabase.functions.invoke('link-preview', {
  body: { url: pastedLink },
})
```

`supabase.functions.invoke` sends the signed-in user's session for you. In our test on a Supabase project, a Vimeo link came back in about 8 seconds the first time and under half a second from the table after that:

```json theme={null}
{
  "url": "https://vimeo.com/22439234",
  "title": "The Mountain",
  "duration": 185,
  "thumbnail": "https://i.vimeocdn.com/video/145027281-cf3e3e047a52e2210b26bbcf42fcde909a80a7dd023a757b95af01936d065ec0-d",
  "is_live": false
}
```

`duration` is in seconds. A live stream that hasn't ended has `is_live: true` and no `duration`, so show a "Live" badge instead of a length. It can't be downloaded or transcribed until the stream ends.

Using Lovable, Bolt or Cursor to build the screen? Give it the function's request and response above and ask for a preview card under the link input that shows the thumbnail, the title and the length as `m:ss`.

## Errors to handle

`supabase.functions.invoke` puts any non-2xx answer in `error`. These are the ones to expect:

| Status | What it means | What to show |
| - | - | - |
| `401` | No signed-in user | Ask them to sign in |
| `400` with `code: "INVALID_URL"` | Not a link | "Paste a video link" |
| `400` with `code: "PLAYLIST_NOT_SUPPORTED"` | A playlist page | Ask for a single video link |
| `402` with `code: "INSUFFICIENT_BALANCE"` | Your Importly balance is empty | Nothing was charged; add credits |
| `422` with `code: "VIDEO_UNAVAILABLE"` or `"VIDEO_PRIVATE"` | The video is gone or private | Say so on the card |
| `202` | The lookup took longer than 30 seconds | Try again in a moment; the next call is quick once it's saved |

Every Importly error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.md).

## In production

* Some sites' thumbnails expire. TikTok's thumbnail links are signed and stop working after a while (ours carried an `x-expires` about two days out). If cards stay on screen for longer, copy the image into a Storage bucket when you save the row, or look the link up again when the thumbnail fails to load.
* Check the length before a bigger job: reject anything over your limit before you pay to [download](/docs/features/downloads.md) or [transcribe](/docs/features/transcripts.md) it.
* For the description, uploader, upload date or view counts, call [`POST /metadata`](/docs/endpoints/metadata) instead. It costs the same and returns everything the source exposes.
* Saving previews in the background (a feed, a bulk import)? Pass a `webhookUrl` and save the row when Importly calls you back, the way [Save transcripts to Supabase](/docs/integrations/supabase-edge-functions.md) does. See [Webhooks](/docs/webhooks.md).

> [!NOTE]
>
> A preview costs \$0.003 per link the first time, and status checks are free. Links already in your table cost nothing. Try it free, no card required. See [Pricing & credits](/docs/billing.md).

Using Claude Code, Cursor or Lovable's chat on this project? Connect the [MCP server](/docs/integrations/mcp.md) and ask it to add link previews with Importly: it reads the same integration guide 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.