> ## 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 Firestore from Cloud Functions

> A tested Firebase recipe: start a transcript from a callable Cloud Function, receive Importly's signed webhook in an HTTPS function, save the result to Firestore, and sweep up any job whose webhook was missed.

If your app runs on Firebase, a video transcript is the feature that breaks once it ships: the code that worked on your laptop gets blocked from Google Cloud's servers, and many videos have no captions to read. Send the link to Importly from a Cloud Function instead and save what comes back in Firestore.

This recipe is three functions and one collection:

* `startTranscript`, a callable function, starts the job for a signed-in user and creates a `transcripts/{jobId}` document.
* `importlyWebhook` receives Importly's signed webhook and fills in the document.
* `sweepTranscripts` runs every five minutes and finishes any document whose webhook never arrived.

Your app reads the document with the normal Firebase SDK, so it never sees your Importly key. Tested with `firebase-functions` 7 and `firebase-admin` 14 (2nd gen functions, Node 22) against the Firestore emulator.

## 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 in Secret Manager:

```bash theme={null}
firebase functions:secrets:set IMPORTLY_API_KEY
firebase functions:secrets:set IMPORTLY_WEBHOOK_SECRET
```

Each function lists the secrets it reads, and only those are available to it. For the emulator, put the two values in `functions/.secret.local` and keep that file out of git.

## 2. The functions

All three live in one file. `saveJob` is shared: the webhook and the sweep both read the job from the status endpoint with your key and save it in a transaction that only updates a document still `queued` or `running`, so a second delivery, or the sweep finding a job the webhook already saved, does nothing.

```ts functions/src/index.ts theme={null}
import crypto from 'node:crypto'
import { initializeApp } from 'firebase-admin/app'
import { FieldValue, getFirestore } from 'firebase-admin/firestore'
import { defineSecret } from 'firebase-functions/params'
import { HttpsError, onCall, onRequest, type FunctionsErrorCode } from 'firebase-functions/v2/https'
import { onSchedule } from 'firebase-functions/v2/scheduler'

initializeApp()
const db = getFirestore()

const IMPORTLY_API_KEY = defineSecret('IMPORTLY_API_KEY')
const IMPORTLY_WEBHOOK_SECRET = defineSecret('IMPORTLY_WEBHOOK_SECRET')
const REGION = 'us-central1'

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

// Read the job from the API and save it to its document, once
const saveJob = async (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

  const ref = db.collection('transcripts').doc(jobId)
  await db.runTransaction(async (tx) => {
    const doc = await tx.get(ref)
    // a second delivery, or the sweep after the webhook, does nothing
    if (!doc.exists || !['queued', 'running'].includes(doc.get('status'))) return
    tx.update(ref, {
      status: job.status,
      text: job.result?.text ?? null,
      segments: job.result?.data?.segments ?? null,
      errorCode: job.code ?? null,
      errorMessage: job.message ?? null,
      updatedAt: FieldValue.serverTimestamp(),
    })
  })
}

const ERROR_CODES: Record<number, FunctionsErrorCode> = {
  400: 'invalid-argument', // a bad or unsupported link
  402: 'failed-precondition', // balance too low
  429: 'resource-exhausted',
}

export const startTranscript = onCall({ region: REGION, secrets: [IMPORTLY_API_KEY] }, async (request) => {
  if (!request.auth) throw new HttpsError('unauthenticated', 'Sign in first')
  const url = request.data?.url
  if (typeof url !== 'string') throw new HttpsError('invalid-argument', 'Send a url')

  const { status, 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: `https://${REGION}-${process.env.GCLOUD_PROJECT}.cloudfunctions.net/importlyWebhook`,
  })
  if (!body.success) {
    throw new HttpsError(ERROR_CODES[status] ?? 'internal', body.error, { code: body.code })
  }

  const { jobId } = body.data
  await db.collection('transcripts').doc(jobId).set({
    userId: request.auth.uid,
    url,
    status: body.data.status,
    createdAt: FieldValue.serverTimestamp(),
  })
  return { id: jobId, status: body.data.status }
})

const verifyImportlySignature = (header: string | undefined, 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 expected = crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')
  return signatures.some((signature) =>
    signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)))
}

export const importlyWebhook = onRequest(
  { region: REGION, secrets: [IMPORTLY_API_KEY, IMPORTLY_WEBHOOK_SECRET] },
  async (req, res) => {
    // rawBody: the signature covers the exact bytes Importly sent
    const rawBody = req.rawBody?.toString('utf8') ?? ''
    if (req.method !== 'POST' || !verifyImportlySignature(req.get('Importly-Signature'), rawBody, IMPORTLY_WEBHOOK_SECRET.value())) {
      res.sendStatus(400)
      return
    }
    const { data } = JSON.parse(rawBody)
    if (data?.type === 'transcribe' && typeof data.jobId === 'string') await saveJob(data.jobId)
    res.sendStatus(200)
  },
)

// Each job gets one webhook delivery and no retries: finish any that were missed
export const sweepTranscripts = onSchedule(
  { schedule: 'every 5 minutes', region: REGION, secrets: [IMPORTLY_API_KEY] },
  async () => {
    const fiveMinutesAgo = Date.now() - 5 * 60 * 1000
    const pending = await db.collection('transcripts').where('status', 'in', ['queued', 'running']).limit(100).get()
    for (const doc of pending.docs) {
      if (doc.get('createdAt')?.toMillis() < fiveMinutesAgo) await saveJob(doc.id)
    }
  },
)
```

`startTranscript`: `"mode": "auto"` uses the video's captions and falls back to speech-to-text when there are none, and `webhookUrl` points at `importlyWebhook`. A rejected request (a bad link, a key problem, or a low balance) throws an `HttpsError` with Importly's `code` in `details`, and no document is written. See [Error handling](/docs/error-handling.md).

`importlyWebhook`: Firebase keeps the exact bytes of the request in `req.rawBody`, which is what the signature covers. The handler takes only the `jobId` from the payload and reads the result from the API with your key. 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).

`sweepTranscripts`: each job gets one webhook delivery and no retries. The sweep also covers the emulator: the webhook URL must be public `https://`, so a function on `localhost` never receives it.

If you deploy to another region, change `REGION`; the webhook URL is built from it and the project ID.

## 3. Security rules

Signed-in users can read their own transcripts. Only the functions, which use the Admin SDK, write them:

```js firestore.rules theme={null}
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /transcripts/{jobId} {
      allow read: if request.auth != null && request.auth.uid == resource.data.userId;
      allow write: if false;
    }
  }
}
```

## 4. Deploy and call it

```bash theme={null}
firebase deploy --only functions,firestore:rules
```

Cloud Functions need the Blaze plan. The first deploy of the sweep turns on Cloud Scheduler for the project.

From your app, start a transcript and listen for the result:

```ts theme={null}
import { doc, getFirestore, onSnapshot } from 'firebase/firestore'
import { getFunctions, httpsCallable } from 'firebase/functions'

const startTranscript = httpsCallable<{ url: string }, { id: string; status: string }>(getFunctions(), 'startTranscript')
const { data } = await startTranscript({ url: 'https://www.youtube.com/watch?v=jNQXAC9IVRw' })

onSnapshot(doc(getFirestore(), 'transcripts', data.id), (snapshot) => {
  const transcript = snapshot.data()
  if (transcript?.status === 'completed') showTranscript(transcript.text)
  if (transcript?.status === 'failed') showError(transcript.errorMessage)
})
```

`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

Using Claude Code, Cursor or Firebase Studio 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.