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

# Save transcripts in Convex from a verified webhook

> A tested Convex recipe: start a transcript from an action, receive Importly's signed webhook in an HTTP action, save the result once with a mutation, and sweep up any job whose webhook was missed with a cron.

If your app runs on Convex, including apps built with Convex's Chef, a video transcript is the feature that breaks once it ships: code that worked on your laptop gets blocked from cloud servers, and many videos have no captions to read. Send the link to Importly from a Convex action instead and save what comes back in a table.

This recipe is four files in your `convex/` folder:

* `schema.ts` adds a `transcripts` table.
* `importly.ts` has the `start` action your app calls, the internal functions that save a finished job once, and the `get` query your app reads.
* `http.ts` receives Importly's signed webhook.
* `crons.ts` finishes any job whose webhook never arrived.

Your app reads the transcript with `useQuery`, so it never sees your Importly key, and the page updates on its own when the transcript is saved. Tested with `convex` 1.51 and `convex-test` against a mocked API, plus a live call with a bad key.

## 1. Add your keys

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. Set both on your deployment:

```bash theme={null}
npx convex env set IMPORTLY_API_KEY imp_...
npx convex env set IMPORTLY_WEBHOOK_SECRET whsec_...
```

Run the same commands with `--prod` for your production deployment. `CONVEX_SITE_URL`, which the webhook URL is built from, is set by Convex for you.

## 2. The table

```ts convex/schema.ts theme={null}
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'

export default defineSchema({
  transcripts: defineTable({
    userId: v.string(),
    url: v.string(),
    jobId: v.string(),
    status: v.string(), // queued, running, completed or failed
    text: v.optional(v.string()),
    segments: v.optional(v.array(v.object({ start: v.number(), end: v.number(), text: v.string() }))),
    errorCode: v.optional(v.string()),
    errorMessage: v.optional(v.string()),
  })
    .index('by_jobId', ['jobId'])
    .index('by_status', ['status']),
})
```

If you already have a schema, add the `transcripts` table to it.

## 3. Start a transcript and save the result

```ts convex/importly.ts theme={null}
import { ConvexError, v } from 'convex/values'
import { action, internalAction, internalMutation, internalQuery, query } from './_generated/server'
import { internal } from './_generated/api'
import type { Id } from './_generated/dataModel'

const importly = async (path: string, body?: object) => {
  const res = await fetch(`https://api.importly.io${path}`, {
    method: body ? 'POST' : 'GET',
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: body ? JSON.stringify(body) : undefined,
  })
  return res.json()
}

// Called from your app: start a transcript for the signed-in user
export const start = action({
  args: { url: v.string() },
  handler: async (ctx, { url }): Promise<Id<'transcripts'>> => {
    const identity = await ctx.auth.getUserIdentity()
    if (!identity) throw new ConvexError({ code: 'UNAUTHENTICATED', message: 'Sign in first' })

    const body = await importly('/transcribe', {
      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: `${process.env.CONVEX_SITE_URL}/importly-webhook`,
    })
    if (!body.success) throw new ConvexError({ code: body.code, message: body.error })

    return await ctx.runMutation(internal.importly.create, {
      userId: identity.subject,
      url,
      jobId: body.data.jobId,
      status: body.data.status,
    })
  },
})

export const create = internalMutation({
  args: { userId: v.string(), url: v.string(), jobId: v.string(), status: v.string() },
  handler: (ctx, args) => ctx.db.insert('transcripts', args),
})

// Read the job from the API and save it, once
export const saveJob = internalAction({
  args: { jobId: v.string() },
  handler: async (ctx, { jobId }) => {
    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 ctx.runMutation(internal.importly.finish, {
      jobId,
      status: job.status,
      text: job.result?.text,
      segments: job.result?.data?.segments?.map(({ start, end, text }: { start: number; end: number; text: string }) => ({ start, end, text })),
      errorCode: job.code,
      errorMessage: job.message,
    })
  },
})

export const finish = internalMutation({
  args: {
    jobId: v.string(),
    status: v.string(),
    text: v.optional(v.string()),
    segments: v.optional(v.array(v.object({ start: v.number(), end: v.number(), text: v.string() }))),
    errorCode: v.optional(v.string()),
    errorMessage: v.optional(v.string()),
  },
  handler: async (ctx, { jobId, ...result }) => {
    const doc = await ctx.db.query('transcripts').withIndex('by_jobId', (q) => q.eq('jobId', jobId)).unique()
    // a second delivery, or the sweep after the webhook, does nothing
    if (!doc || (doc.status !== 'queued' && doc.status !== 'running')) return
    await ctx.db.patch(doc._id, result)
  },
})

// Each job gets one webhook delivery and no retries: finish any that were missed
export const pending = internalQuery({
  args: {},
  handler: async (ctx) => {
    const fiveMinutesAgo = Date.now() - 5 * 60 * 1000
    const docs = [
      ...(await ctx.db.query('transcripts').withIndex('by_status', (q) => q.eq('status', 'queued')).take(100)),
      ...(await ctx.db.query('transcripts').withIndex('by_status', (q) => q.eq('status', 'running')).take(100)),
    ]
    return docs.filter((doc) => doc._creationTime < fiveMinutesAgo).map((doc) => doc.jobId)
  },
})

export const sweep = internalAction({
  args: {},
  handler: async (ctx) => {
    const jobIds: string[] = await ctx.runQuery(internal.importly.pending)
    for (const jobId of jobIds) await ctx.runAction(internal.importly.saveJob, { jobId })
  },
})

// Called from your app: the signed-in user's transcript
export const get = query({
  args: { id: v.id('transcripts') },
  handler: async (ctx, { id }) => {
    const identity = await ctx.auth.getUserIdentity()
    const doc = await ctx.db.get(id)
    if (!identity || !doc || doc.userId !== identity.subject) return null
    return doc
  },
})
```

`start`: `"mode": "auto"` uses the video's captions and falls back to speech-to-text when there are none, and `webhookUrl` points at the HTTP action below. A rejected request (a bad link, a key problem, or a low balance) throws a `ConvexError` with Importly's `code` and message, and nothing is saved. See [Error handling](/docs/error-handling.md). The `Promise<Id<'transcripts'>>` return type is there because the action returns the result of `runMutation`: without it, TypeScript can't infer the type.

`saveJob` and `finish`: the webhook and the sweep both read the job from the status endpoint with your key, then save it in a mutation that only updates a transcript still `queued` or `running`. A second delivery, or the sweep finding a job the webhook already saved, does nothing.

Sign-in: the action and the query use `ctx.auth`, so they work with Convex Auth, Clerk or any other auth provider you've set up in Convex.

## 4. Receive the webhook

```ts convex/http.ts theme={null}
import { httpRouter } from 'convex/server'
import { httpAction } from './_generated/server'
import { internal } from './_generated/api'

const hex = (buffer: ArrayBuffer) => [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, '0')).join('')

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])
  const signatures = parts.filter(([key]) => key === 'v1').map(([, value]) => value ?? '')
  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, ['sign'])
  const expected = hex(await crypto.subtle.sign('HMAC', key, encoder.encode(`${timestamp}.${rawBody}`)))
  // compare every character, so the time taken doesn't reveal how much matched
  return signatures.some((signature) => {
    if (signature.length !== expected.length) return false
    let diff = 0
    for (let i = 0; i < expected.length; i++) diff |= signature.charCodeAt(i) ^ expected.charCodeAt(i)
    return diff === 0
  })
}

const http = httpRouter()

http.route({
  path: '/importly-webhook',
  method: 'POST',
  handler: httpAction(async (ctx, request) => {
    // the signature covers the exact bytes Importly sent
    const rawBody = await request.text()
    const isValid = await verifyImportlySignature(request.headers.get('Importly-Signature'), rawBody, process.env.IMPORTLY_WEBHOOK_SECRET!)
    if (!isValid) return new Response(null, { status: 400 })

    const { data } = JSON.parse(rawBody)
    if (data?.type === 'transcribe' && typeof data.jobId === 'string') {
      await ctx.scheduler.runAfter(0, internal.importly.saveJob, { jobId: data.jobId })
    }
    return new Response(null, { status: 200 })
  }),
})

export default http
```

HTTP actions run in Convex's default runtime, so the check uses Web Crypto instead of `node:crypto`. It reads the raw body with `request.text()`, because the signature covers the exact bytes Importly sent. 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).

The handler takes only the `jobId` from the payload, schedules `saveJob` and answers `200` straight away. `saveJob` reads the result from the API with your key, so a forged request can't put data into your app.

## 5. Sweep up missed webhooks

```ts convex/crons.ts theme={null}
import { cronJobs } from 'convex/server'
import { internal } from './_generated/api'

const crons = cronJobs()
crons.interval('finish missed transcripts', { minutes: 5 }, internal.importly.sweep)
export default crons
```

Each job gets one webhook delivery and no retries. The sweep also covers local development: the webhook URL must be public `https://`, so a [local deployment](https://docs.convex.dev/cli/local-deployments) never receives it, while a cloud dev deployment does.

## 6. Call it from your app

```tsx theme={null}
import { useAction, useQuery } from 'convex/react'
import { useState } from 'react'
import { api } from '../convex/_generated/api'
import type { Id } from '../convex/_generated/dataModel'

export const TranscriptForm = () => {
  const start = useAction(api.importly.start)
  const [id, setId] = useState<Id<'transcripts'> | null>(null)
  const transcript = useQuery(api.importly.get, id ? { id } : 'skip')

  const onSubmit = async (url: string) => setId(await start({ url }))

  if (transcript?.status === 'completed') return <p>{transcript.text}</p>
  if (transcript?.status === 'failed') return <p>{transcript.errorMessage}</p>
  if (transcript) return <p>Transcribing…</p>

  return (
    <form onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get('url'))) }}>
      <input name="url" placeholder="Paste a video or audio link" />
      <button type="submit">Transcribe</button>
    </form>
  )
}
```

`segments` holds the same transcript with `start` and `end` times in seconds, for captions, chapters or search. A job that fails later, for example because the video is private, is saved with `status: 'failed'` and its `errorCode` and `errorMessage`.

## 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 `saveJob`. 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

Building in Chef, Claude Code or Cursor? 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.