Next.js embed youtube video
By Flavio Copes
Learn how to embed a YouTube video in a Next.js page: just drop in an iframe pointing at the youtube.com/embed URL with the video id.
To embed a YouTube video in a Next.js page, add an iframe pointing at the video’s youtube.com/embed URL. It’s plain HTML, so it works the same in the App Router and the Pages Router, in server components and client components.
<iframe
className='w-full aspect-video self-stretch md:min-h-96'
src='https://www.youtube.com/embed/dQw4w9WgXcQ'
title='Rick Astley - Never Gonna Give You Up'
/>
The video id is the part after watch?v= in the video’s URL. Take youtube.com/watch?v=dQw4w9WgXcQ, and the id is dQw4w9WgXcQ.
A few things about this snippet. We’re in JSX, so the attribute is className, not class. The Tailwind aspect-video class keeps the player at a 16:9 ratio at any width, so you don’t hardcode a height. And the title attribute tells screen readers what the iframe contains, so don’t skip it.
Fullscreen and player features
By default the embedded player won’t go fullscreen. Add allowFullScreen (camelCase, since this is JSX), plus the allow attribute for the other player features:
<iframe
className='w-full aspect-video'
src='https://www.youtube.com/embed/dQw4w9WgXcQ'
title='Rick Astley - Never Gonna Give You Up'
allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture'
allowFullScreen
/>
If you care about cookies, swap the host for www.youtube-nocookie.com. Same embed URL format, but YouTube’s privacy-enhanced mode holds off on tracking cookies until the visitor actually plays the video.
Watch out for the wrong URL
The one mistake everyone makes at least once: pasting the regular watch URL into the iframe src, like https://www.youtube.com/watch?v=dQw4w9WgXcQ.
That renders a gray box saying “www.youtube.com refused to connect”. YouTube blocks its watch pages from being loaded inside frames. Only the /embed/ URLs are allowed in an iframe, so the fix is switching the path from watch?v=ID to embed/ID.
An alternative for performance
A YouTube iframe loads a lot of JavaScript, even before anyone hits play. If that hurts your page scores, Next.js has an official helper in the @next/third-parties package:
import { YouTubeEmbed } from '@next/third-parties/google'
<YouTubeEmbed videoid='dQw4w9WgXcQ' />
It renders a lightweight preview first and only loads the real player on interaction. For a single video on a page, the plain iframe is fine.
Related posts about next: