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

# Save transcripts to Supabase from an Edge Function

> A tested Supabase recipe: start a transcript from an Edge Function, receive Importly's signed webhook in a second function, save the result to a Postgres table with RLS, and sweep up any job whose webhook was missed.

If your app runs on Supabase (Lovable and Bolt apps often do), a video transcript is the feature that breaks once it ships: the code that worked in the preview gets blocked from a server, and many videos have no captions to read. Edge Functions can't run a downloader binary anyway. Send the link to Importly instead and save what comes back in your database.

This recipe is three functions and one table:

* `start-transcript` starts the job for a signed-in user and stores its ID in a `transcripts` row.
* `importly-webhook` receives Importly's signed webhook and fills in the row.
* `sweep-transcripts` runs every few minutes and finishes any row whose webhook never arrived.

Your frontend reads the row with the normal Supabase client, so it never sees your Importly key. For a simpler start without a table or webhook, see [Lovable, Bolt & Replit](/docs/integrations/app-builders.md).

## 1. Add your 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:

```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, so you don't set those. For `supabase functions serve`, put the two Importly values 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. Signed-in users can read their own rows; only the functions (with the service role key) write them.

```sql theme={null}
create table public.transcripts (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  url text not null,
  job_id text not null unique,
  status text not null default 'queued',
  text text,
  segments jsonb,
  error_code text,
  error_message text,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

alter table public.transcripts enable row level security;

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

## 3. Shared helper

Both the webhook and the sweep save a job the same way: they read it from the status endpoint with your key and update its row. The `status in (queued, running)` filter makes a second delivery, or the sweep finding a job the webhook already saved, do nothing.

```ts supabase/functions/_shared/importly.ts theme={null}
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2'

const API = 'https://api.importly.io'

export const importly = async (path: string, init: RequestInit = {}) => {
  const res = await fetch(`${API}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${Deno.env.get('IMPORTLY_API_KEY')}`,
      'Content-Type': 'application/json',
    },
  })
  return { status: res.status, body: await res.json() }
}

// Read the job from the API and save it to its row, once
export const saveJob = async (supabase: SupabaseClient, jobId: string) => {
  const { body } = await importly(`/transcribe/status?id=${encodeURIComponent(jobId)}`)
  if (!body.success) return
  const job = body.data
  if (job.status !== 'completed' && job.status !== 'failed') return

  await supabase
    .from('transcripts')
    .update({
      status: job.status,
      text: job.result?.text ?? null,
      segments: job.result?.data?.segments ?? null,
      error_code: job.code ?? null,
      error_message: job.message ?? null,
      updated_at: new Date().toISOString(),
    })
    .eq('job_id', jobId)
    .in('status', ['queued', 'running'])
}
```

## 4. Start the job

The frontend calls this function with the user's session (Supabase checks the JWT before the function runs). `"mode": "auto"` uses the video's captions and falls back to speech-to-text when there are none, and `webhookUrl` points at the next function.

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

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()
  const { status, body } = await importly('/transcribe', {
    method: 'POST',
    body: JSON.stringify({
      url,
      // captions when the video has them, speech-to-text when it doesn't
      mode: 'auto',
      // stop a long video without captions before it costs more than $0.50
      maxCostDollars: 0.5,
      webhookUrl: `${Deno.env.get('SUPABASE_URL')}/functions/v1/importly-webhook`,
    }),
  })
  if (!body.success) return Response.json({ error: body.error, code: body.code }, { status })

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

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

A rejected request (a bad link, a key problem, or a low balance) comes back with its HTTP status, an `error` and a `code`, and no row is written. See [Error handling](/docs/error-handling.md).

## 5. Receive the webhook

Importly can't send a Supabase JWT, so turn off the JWT check for this one function. The signature check below is what keeps other callers out.

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

Deno has Web Crypto built in, and `crypto.subtle.verify` compares the signature in constant time. The handler takes only the `jobId` from the payload and reads the result from the API with your key:

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

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 { data } = JSON.parse(rawBody)
  if (data?.type === 'transcribe' && typeof data.jobId === 'string') {
    await saveJob(supabase, data.jobId)
  }
  return new Response(null, { status: 200 })
})
```

A job that fails later, for example because the video is private, is saved with `status: 'failed'` and its `error_code` and `error_message`. Right after you rotate the signing secret, Importly sends two `v1` signatures for 24 hours, and this check accepts either. See [Webhooks](/docs/webhooks.md#verify-signatures).

## 6. Catch missed webhooks

Each job gets one webhook delivery and no retries. This function checks rows that have been pending for more than five minutes:

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

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

Deno.serve(async () => {
  const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000).toISOString()
  const { data: rows } = await supabase
    .from('transcripts')
    .select('job_id')
    .in('status', ['queued', 'running'])
    .lt('created_at', fiveMinutesAgo)
    .limit(50)

  for (const row of rows ?? []) await saveJob(supabase, row.job_id)
  return Response.json({ checked: rows?.length ?? 0 })
})
```

Run it every five minutes with [Supabase Cron](https://supabase.com/docs/guides/functions/schedule-functions). It also covers local development: the webhook URL must be public `https://`, so a function served on `localhost` never receives it.

## 7. Deploy and call it

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

From your app, start a transcript and read the row back:

```ts theme={null}
const { data: row, error } = await supabase.functions.invoke('start-transcript', {
  body: { url: 'https://www.youtube.com/watch?v=jNQXAC9IVRw' },
})

// later, or from a Realtime subscription on the transcripts table
const { data } = await supabase.from('transcripts').select('status, text, segments').eq('id', row.id).single()
```

`segments` holds the same transcript with `start` and `end` times in seconds, for captions, chapters or search.

## Downloading the file instead

For the video or audio file itself, start [`POST /import`](/docs/endpoints/import) the same way and save `mediaUrl` from [`GET /import/status`](/docs/endpoints/import-status) in the helper. That link is valid for 7 days, so store the file if your app needs it longer: with `store: true`, each import is copied to your own S3 or R2 bucket ([recipe](/docs/integrations/save-to-bucket.md)). Set `includeVideo: false` for audio only. See [Downloads](/docs/features/downloads.md).

> [!NOTE]
>
> A transcript from captions costs $0.003. Speech-to-text for a video without captions is $0.01 per minute, and `maxCostDollars` stops a long one before it's charged. Try it free, no card required. See [Pricing & credits](/docs/billing.md).

## Let your agent write it

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