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

# Add transcripts to a Next.js app

> A working Next.js App Router recipe: a user pastes a video link and gets the transcript back, with route handlers for the API call, polling, and a webhook for production.

This recipe adds "paste a link, get a transcript" to a Next.js app using the App Router. It works the same on Vercel or any other host, including videos with no captions. The key stays on the server: the browser only talks to your own route handlers.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and add it to `.env.local`, and to your host's environment variables (on Vercel: **Settings → Environment Variables**):

```bash .env.local theme={null}
IMPORTLY_API_KEY=your_api_key
```

Don't prefix it with `NEXT_PUBLIC_`: that would ship it to the browser.

## 2. Start the transcript

This route handler sends the link to Importly. `"mode": "auto"` uses the video's captions and falls back to speech-to-text when there are none, and `wait` holds the request until the transcript is ready, so a captioned video usually comes back in this one call.

```ts app/api/transcribe/route.ts theme={null}
import { toResult } from '@/lib/importly'

export const maxDuration = 60

export async function POST(request: Request) {
  const { url } = await request.json()

  const res = await fetch('https://api.importly.io/transcribe', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    // wait up to 25s for the result; cap speech-to-text on long videos at $0.50
    body: JSON.stringify({ url, mode: 'auto', wait: 25, maxCostDollars: 0.5 }),
  })

  const body = await res.json()
  if (!res.ok || !body.success) {
    return Response.json({ status: 'failed', message: body.error, code: body.code }, { status: res.status })
  }

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

Both routes hand the browser the same small shape:

```ts lib/importly.ts theme={null}
// Same shape for a finished, failed or still-running job
export const toResult = (data: any) => ({
  jobId: data.jobId,
  status: data.status,
  text: data.result?.text,
  segments: data.result?.data?.segments,
  message: data.message,
  code: data.code,
})
```

A rejected request (a bad link, a key problem, or a low balance) comes back with an HTTP error and an `error` message. A job that fails later, for example because the video is private, comes back with `status: "failed"`, a `code` and a `message`. See [Error handling](/docs/error-handling.md).

## 3. Poll if it's still running

Long videos without captions take longer than `wait`. Then the response has `status: "queued"` or `"running"` and a `jobId`, and the browser asks this route until it's done:

```ts app/api/transcribe/[id]/route.ts theme={null}
import { toResult } from '@/lib/importly'

export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params

  const res = await fetch(`https://api.importly.io/transcribe/status?id=${encodeURIComponent(id)}`, {
    headers: { Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}` },
    cache: 'no-store',
  })

  const body = await res.json()
  if (!res.ok || !body.success) {
    return Response.json({ status: 'failed', message: body.error, code: body.code }, { status: res.status })
  }

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

## 4. The form

```tsx app/transcript-form.tsx theme={null}
'use client'

import { useState } from 'react'

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export const TranscriptForm = () => {
  const [url, setUrl] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [text, setText] = useState('')
  const [error, setError] = useState('')

  const onSubmit = async (event: React.FormEvent) => {
    event.preventDefault()
    setIsLoading(true)
    setText('')
    setError('')

    let job = await fetch('/api/transcribe', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ url }),
    }).then((res) => res.json())

    while (job.status === 'queued' || job.status === 'running') {
      await sleep(3000)
      job = await fetch(`/api/transcribe/${job.jobId}`).then((res) => res.json())
    }

    setIsLoading(false)
    if (job.status !== 'completed') return setError(job.message ?? 'Something went wrong')
    setText(job.text)
  }

  return (
    <form onSubmit={onSubmit}>
      <input value={url} onChange={(event) => setUrl(event.target.value)} placeholder="Paste a YouTube, TikTok or podcast link" />
      <button disabled={isLoading}>{isLoading ? 'Transcribing…' : 'Get transcript'}</button>
      {error && <p>{error}</p>}
      {text && <pre style={{ whiteSpace: 'pre-wrap' }}>{text}</pre>}
    </form>
  )
}
```

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

## 5. In production: save results with a webhook

When the transcript belongs to a record in your database (a saved video, a user's library), don't keep the browser waiting. Start the job with a `webhookUrl` and save the result when Importly calls you back:

```ts theme={null}
body: JSON.stringify({ url, mode: 'auto', maxCostDollars: 0.5, webhookUrl: `${process.env.APP_URL}/api/webhooks/importly` }),
```

Store `jobId` with your record. Importly sends one `POST` when the job finishes. This handler takes only the `jobId` from it and reads the result from the API with your key, so a forged request can't put data into your app. Every delivery is also signed: to reject forged requests before calling the API, check the `Importly-Signature` header as shown in [Verify signatures](/docs/webhooks.md#verify-signatures):

```ts app/api/webhooks/importly/route.ts theme={null}
export async function POST(request: Request) {
  const { data } = await request.json()
  if (data?.type !== 'transcribe' || typeof data.jobId !== 'string') return new Response(null, { status: 200 })

  const res = await fetch(`https://api.importly.io/transcribe/status?id=${encodeURIComponent(data.jobId)}`, {
    headers: { Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}` },
    cache: 'no-store',
  })
  const body = await res.json()
  if (!body.success) return new Response(null, { status: 200 })

  const job = body.data
  if (job.status === 'completed') {
    // find your record by job.jobId and save job.result.text and job.result.data.segments
  }
  if (job.status === 'failed') {
    // mark the record failed with job.code and job.message
  }

  return new Response(null, { status: 200 })
}
```

Each job gets one delivery and no retries, so also check jobs that have been pending for a few minutes with the status endpoint. The webhook URL must be public `https://`, so a `localhost` app gets nothing: use polling in development. See [Webhooks](/docs/webhooks.md).

## Downloading the file instead

For the video or audio file itself, send the link to [`POST /import`](/docs/endpoints/import) and read [`GET /import/status`](/docs/endpoints/import-status) the same way. The finished job has `result.mediaUrl`, a link to the file that's valid for 7 days. Set `includeVideo: false` for audio only, or `store: true` to have it copied to your own bucket ([recipe](/docs/integrations/save-to-bucket.md)). `/import` has no `wait`, so use polling or a webhook. 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 or Cursor on this app? 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.