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

# Get a YouTube transcript in Next.js

> One Next.js App Router route handler that takes a YouTube link and returns the transcript text and timestamped segments, including videos with no captions.

You want a Next.js route that takes a YouTube link and returns the transcript. Scraping captions from a Vercel function gets blocked, and many videos have no captions at all. This route sends the link to Importly, which uses the captions when there are some and speech-to-text when there aren't, and returns the result in the same request.

## The route

```ts app/api/youtube-transcript/route.ts theme={null}
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',
    },
    // captions or speech-to-text; wait up to 25s; cap speech-to-text at $0.50
    body: JSON.stringify({ url, mode: 'auto', wait: 25, maxCostDollars: 0.5 }),
  })
  const body = await res.json()

  // Rejected up front: bad link, bad key, low balance or rate limit
  if (!res.ok || !body.success) {
    return Response.json({ error: body.error, code: body.code }, { status: res.status })
  }

  const job = body.data
  if (job.status === 'failed') {
    // e.g. VIDEO_PRIVATE or MAX_COST_EXCEEDED. Failed transcriptions are refunded.
    return Response.json({ error: job.message, code: job.code }, { status: 422 })
  }
  if (job.status !== 'completed') {
    // A long video without captions is still running: poll GET /transcribe/status with this id
    return Response.json({ jobId: job.jobId, status: job.status }, { status: 202 })
  }

  return Response.json({
    text: job.result.text,
    segments: job.result.data.segments,
    source: job.result.source,
  })
}
```

Put the key in `.env.local` and in your host's environment variables as `IMPORTLY_API_KEY`, without a `NEXT_PUBLIC_` prefix, so it never reaches the browser. Create it on the [API key page](https://www.importly.io/dashboard/api-key).

```bash theme={null}
curl -X POST http://localhost:3000/api/youtube-transcript \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://www.youtube.com/watch?v=jNQXAC9IVRw" }'
```

## What comes back

```json theme={null}
{
  "text": "All right, so here we are, in front of the elephants\n...",
  "segments": [
    { "start": 1.2, "end": 3.36, "text": "All right, so here we are, in front of the elephants" },
    { "start": 5.318, "end": 7.974, "text": "the cool thing about these guys is that they have really..." }
  ],
  "source": "platform_captions"
}
```

`source` is `platform_captions` when the video's own captions were used and speech-to-text otherwise. Segment times are in seconds, ready for subtitles, chapters or search. Shorts and `youtu.be` links work the same way.

## Errors to handle

| What you see | Cause | What to do |
| - | - | - |
| `400` `INVALID_URL` | Not a video link | Ask the user for a video link |
| `402` `INSUFFICIENT_BALANCE` | Balance too low | Add credits; nothing was charged |
| `failed` with `VIDEO_PRIVATE` / `VIDEO_UNAVAILABLE` | Private or removed video | Tell the user |
| `failed` with `MAX_COST_EXCEEDED` | Long video without captions costs more than `maxCostDollars` | Raise the cap or skip it |
| `202` with a `jobId` | Still running after `wait` | Poll `GET /transcribe/status?id=...` every few seconds |

## Polling, a form and webhooks

The [Next.js recipe](/docs/integrations/nextjs.md) adds the polling route, a client form and a webhook for saving transcripts to your database. Options such as language and your own speech-to-text key are in [Transcripts](/docs/features/transcripts.md).

> [!NOTE]
>
> A transcript from captions costs $0.003. Speech-to-text is $0.01 per minute. Try it free, no card required. See [Pricing & credits](/docs/billing.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.