The fastest way to add a YouTube embed in Astro is a facade: render the video’s thumbnail and a play button as plain HTML, then swap in the real <iframe> only when someone clicks. A standard YouTube iframe downloads the player and its scripts as soon as the page loads, even if nobody presses play. A facade component in Astro costs one image until the visitor asks for the video.
This guide builds that component from scratch, shows the ready-made astro-embed option, and covers privacy, MDX use and video structured data.
Key Takeaways
- A plain YouTube iframe loads the full player up front and often hurts LCP and Total Blocking Time.
- A facade shows
i.ytimg.comthumbnail art and loads the iframe on click.- Wrap the thumbnail in a real link to the video, so it works without JavaScript.
- Use
youtube-nocookie.comfor the embed to reduce tracking before playback.@astro-community/astro-embed-youtubegives you a tested facade in one import.
Why the default YouTube embed is slow
YouTube’s “Share, Embed” code is a single iframe, but the iframe itself pulls in the YouTube player: several hundred kilobytes of JavaScript, CSS, fonts and tracking requests, before anyone presses play. On a page with two or three videos, that’s often more than the rest of the page combined. Lighthouse flags it under third-party code, and Google’s own performance guidance on web.dev recommends facades for exactly this case.
Adding loading="lazy" to the iframe helps when the video is below the fold, because the browser waits until it’s near the viewport. It does nothing for a video near the top of the page, and the player still loads in full once the visitor scrolls to it.
| Approach | Loads up front | Works without JS | Effort |
|---|---|---|---|
| Plain iframe | Full player | Yes | None |
Iframe with loading="lazy" |
Full player, when near viewport | Yes | One attribute |
| Facade component | One thumbnail image | Yes, as a link | One component |
astro-embed package |
One thumbnail plus a small script | Shows a link | One import |
Astro is a good fit for facades because a component renders to static HTML at build time and ships no JavaScript unless you add it. Our zero JavaScript by default explainer covers why that matters.
Build a YouTube facade component
The component outputs a link with the thumbnail inside a custom element. A small script upgrades it into an iframe on click:
---
// src/components/YouTube.astro
interface Props {
id: string;
title: string;
start?: number;
}
const { id, title, start } = Astro.props;
const params = new URLSearchParams({ autoplay: '1', rel: '0' });
if (start) params.set('start', String(start));
const embedUrl = `https://www.youtube-nocookie.com/embed/${id}?${params}`;
const watchUrl = `https://www.youtube.com/watch?v=${id}`;
const poster = `https://i.ytimg.com/vi/${id}/hqdefault.jpg`;
---
<youtube-facade data-embed={embedUrl} data-title={title}>
<a href={watchUrl} class="yt-link">
<img src={poster} alt="" width="480" height="360" loading="lazy" decoding="async" />
<span class="yt-play" aria-hidden="true"></span>
<span class="sr-only">Play video: {title}</span>
</a>
</youtube-facade>
<script>
class YouTubeFacade extends HTMLElement {
connectedCallback() {
const link = this.querySelector('a');
link?.addEventListener(
'click',
(event) => {
event.preventDefault();
const iframe = document.createElement('iframe');
iframe.src = this.dataset.embed!;
iframe.title = this.dataset.title!;
iframe.allow = 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture; fullscreen';
iframe.allowFullscreen = true;
this.replaceChildren(iframe);
iframe.focus();
},
{ once: true },
);
}
}
if (!customElements.get('youtube-facade')) {
customElements.define('youtube-facade', YouTubeFacade);
}
</script>
<style>
youtube-facade {
display: block;
position: relative;
aspect-ratio: 16 / 9;
background: #000;
overflow: hidden;
}
youtube-facade img,
youtube-facade :global(iframe) {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
border: 0;
}
.yt-play {
position: absolute;
top: 50%;
left: 50%;
width: 68px;
height: 48px;
transform: translate(-50%, -50%);
background: rgb(33 33 33 / 0.8);
border-radius: 12px;
}
.yt-play::after {
content: '';
position: absolute;
top: 50%;
left: 55%;
transform: translate(-50%, -50%);
border-style: solid;
border-width: 10px 0 10px 18px;
border-color: transparent transparent transparent #fff;
}
.yt-link:hover .yt-play,
.yt-link:focus-visible .yt-play {
background: #f00;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
}
</style>
Use it with the video ID from the URL (the part after v=):
---
// src/pages/demo.astro
import YouTube from '../components/YouTube.astro';
---
<YouTube id="dQw4w9WgXcQ" title="Product walkthrough" start={30} />
A few design choices are deliberate:
- A real link. Without JavaScript, or if the script fails, clicking opens the video on YouTube. Keyboard and screen reader users get a normal focusable link with a clear label.
- A custom element. Astro bundles the
<script>once per page no matter how many videos you render, and each<youtube-facade>upgrades itself. The element only exists in the browser, so no framework runtime ships. :global(iframe). Astro scopes styles to markup in the component. The iframe is created by JavaScript later, so it needs:global()to receive the sizing rules.aspect-ratio. The box reserves its space before the image loads, so nothing shifts. See preventing layout shift in Astro for more.
Thumbnails and image quality
YouTube serves thumbnails at predictable URLs on i.ytimg.com:
| File | Size | Always available |
|---|---|---|
hqdefault.jpg |
480 x 360 | Yes |
sddefault.jpg |
640 x 480 | Most videos |
maxresdefault.jpg |
1280 x 720 | Only for HD uploads |
hqdefault.jpg is the safe default. It’s 4:3 with black bars top and bottom, which object-fit: cover crops away inside a 16:9 box. maxresdefault.jpg looks sharper on wide layouts, but returns a placeholder image for videos without an HD thumbnail.
To serve a resized WebP or AVIF thumbnail, let Astro’s image service process it. Allow the domain in astro.config.mjs with image: { domains: ['i.ytimg.com'] }, then replace the <img> with <Image /> from astro:assets:
---
// inside src/components/YouTube.astro
import { Image } from 'astro:assets';
---
<Image src={poster} alt="" width={480} height={360} loading="lazy" />
For a custom poster frame, which usually looks better than YouTube’s auto-picked frame, pass a local image as a prop and render it with <Image /> instead. The Astro image component guide covers sizing and formats.
The ready-made option: astro-embed
If you’d rather not maintain your own component, the community astro-embed project includes a YouTube component built on the lite-youtube-embed approach:
npm install @astro-community/astro-embed-youtube
---
// src/pages/demo.astro
import { YouTube } from '@astro-community/astro-embed-youtube';
---
<YouTube id="dQw4w9WgXcQ" />
It accepts a video ID or a full YouTube URL and supports props for a custom poster and player parameters. It’s a good choice when you want a tested facade with sensible defaults. Write your own when you need full control of markup, styling or the no-JS fallback. Check the project’s README for the current props, since community packages change faster than Astro itself.
Use the component in MDX
In MDX files, import the component at the top and use it like any other:
---
title: "Getting started"
---
import YouTube from '../../components/YouTube.astro';
Here's a two-minute walkthrough of the setup:
<YouTube id="dQw4w9WgXcQ" title="Setup walkthrough" />
If many posts embed videos, pass the component through the components prop when rendering, so authors don’t repeat the import. Astro’s MDX integration docs cover custom components in MDX.
Privacy and youtube-nocookie
Embeds from www.youtube.com can set cookies and send tracking requests as soon as the iframe loads. The www.youtube-nocookie.com domain is YouTube’s privacy-enhanced mode: it avoids storing most identifying cookies until the visitor plays the video. Combined with a facade, nothing from YouTube loads before the click except the thumbnail image from i.ytimg.com.
That matters if your site uses a cookie consent banner. Under many privacy regimes, a facade with privacy-enhanced mode is easier to justify than an iframe that loads on page view, though you should still confirm with your own legal guidance. If you run a Content Security Policy, add https://www.youtube-nocookie.com to frame-src and https://i.ytimg.com to img-src. Our Astro Content Security Policy guide shows how to set those directives.
One known quirk: on some mobile browsers, autoplay inside a freshly created iframe is blocked, so visitors may need to tap play a second time. That’s a browser restriction, and every facade implementation has it.
Add VideoObject structured data
If a video is central to the page, VideoObject structured data helps search engines show it in video results. Add it in the page’s head:
---
// src/components/VideoSchema.astro
interface Props {
id: string;
name: string;
description: string;
uploadDate: string;
}
const { id, name, description, uploadDate } = Astro.props;
const schema = {
'@context': 'https://schema.org',
'@type': 'VideoObject',
name,
description,
uploadDate,
thumbnailUrl: `https://i.ytimg.com/vi/${id}/hqdefault.jpg`,
embedUrl: `https://www.youtube-nocookie.com/embed/${id}`,
contentUrl: `https://www.youtube.com/watch?v=${id}`,
};
---
<script type="application/ld+json" set:html={JSON.stringify(schema)} />
uploadDate should be the video’s real publish date in ISO 8601 format, such as 2026-10-15. Only add this to pages where the video is a main part of the content, not to every page with a small embed. The JSON-LD guide for Astro covers validating structured data.
If you’re building a site with a lot of video, such as a course landing page or a band site, the Music & Audio category of Komal themes covers bands, labels and releases, and this component drops into any of them.
FAQ
How do I embed a YouTube video in Astro?
Paste YouTube’s iframe embed code into any .astro or MDX file, and add loading="lazy" if it’s below the fold. For better performance, use a facade component that shows the thumbnail and loads the iframe only when the visitor clicks play.
Does a YouTube embed slow down an Astro site?
A standard iframe does. It downloads the YouTube player and its scripts on page load, which can add hundreds of kilobytes and hurt Core Web Vitals. A facade loads only a thumbnail image until someone presses play, so the page stays as fast as the rest of your Astro site.
What is youtube-nocookie.com?
It’s YouTube’s privacy-enhanced embed domain. Videos embedded from youtube-nocookie.com don’t store most identifying cookies until the visitor plays the video. Swap the domain in your embed URL; the video ID and parameters stay the same.
Can I use lite-youtube-embed in Astro?
Yes. You can load lite-youtube-embed as a web component in a <script>, or use @astro-community/astro-embed-youtube, which wraps the same idea in an Astro component. Writing your own facade, as shown above, takes under 100 lines including styles and has no dependency.
How do I make an embedded YouTube video responsive?
Wrap it in an element with aspect-ratio: 16 / 9 and width: 100%, then make the iframe fill it with width: 100%; height: 100%. The facade component above already does this, so it resizes with its container and reserves space before loading.