Embed YouTube Videos
2 min read
This guide shows how to embed lightweight YouTube videos using lite-youtube-embed in Astro project.
Step-by-Step Guide
Section titled “Step-by-Step Guide”-
Install the dependency
Install the
lite-youtube-embedpackage using your preferred package manager:Terminal window npm add lite-youtube-embedTerminal window pnpm add lite-youtube-embedTerminal window yarn add lite-youtube-embedTerminal window bun add lite-youtube-embed -
Create a
YouTube.astrocomponentCreate a file at
src/components/YouTube.astro:---import "lite-youtube-embed/src/lite-yt-embed.css";export interface Props extends astroHTML.JSX.HTMLAttributes {id: string; // YouTube video ID or URLposter?: string; // Optional custom thumbnailparams?: string; // Optional query parameters (?start=30 etc.)playlabel?: string; // Accessible label for play button}const { id, poster, params, playlabel, ...attrs } = Astro.props as Props;const idRegExp = /^[A-Za-z0-9-_]{11}$/;const urlPattern = /(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9-_]{11})/;function extractVideoId(input: string): string | undefined {if (idRegExp.test(input)) return input;return input.match(urlPattern)?.[1];}const videoId = extractVideoId(id);const posterURL = poster || `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`;---<lite-youtubevideoid={videoId}params={params}playlabel={playlabel}loading="lazy"style={`background-image: url('${posterURL}');`}{...attrs}></lite-youtube><script>import "lite-youtube-embed";</script><style is:global>lite-youtube > iframe {all: unset !important;width: 100% !important;height: 100% !important;position: absolute !important;inset: 0 !important;border: 0 !important;}</style>
Example Usage
Section titled “Example Usage”You can now import and use the <YouTube /> component in any .astro or .mdx file:
---import YouTube from "@/components/YouTube.astro";---
<YouTube id="_NIpfrGXwG8" poster="https://i3.ytimg.com/vi/_NIpfrGXwG8/maxresdefault.jpg"/>Or just pass a full YouTube URL:
<YouTube id="https://www.youtube.com/watch?v=_NIpfrGXwG8" />The following will be rendered on your page: