ScreenshotNeo

BlogHow-to

How to Get a YouTube Video Thumbnail Image in HTML

Show a YouTube thumbnail with its video ID, handle missing sizes, use the Data API, and add reliable metadata to your HTML.

By the ScreenshotNeo team1 October 20268 min read

How to Get a YouTube Video Thumbnail Image in HTML

Quick answer: get the YouTube video ID, build a thumbnail URL such as https://i.ytimg.com/vi/VIDEO_ID/hqdefault.jpg, and place that URL in an HTML image element. Replace VIDEO_ID with the ID from the watch URL.

<img
  src="https://i.ytimg.com/vi/VIDEO_ID/hqdefault.jpg"
  alt="Video thumbnail"
  width="480"
  loading="lazy"
>

This direct URL method is convenient for a quick display. When you need to know which thumbnail sizes actually exist, request the video through the YouTube Data API and use the URL returned in snippet.thumbnails. A thumbnail is a still image; it does not replace the YouTube player iframe.

1. Find the YouTube video ID

The video ID is the value after v= in a standard watch URL. It is usually 11 characters, but treat it as an opaque string rather than validating it by length alone.

URL form Video ID location Example ID
https://www.youtube.com/watch?v=VIDEO_ID Query parameter v VIDEO_ID
https://youtu.be/VIDEO_ID Path segment VIDEO_ID
https://www.youtube.com/shorts/VIDEO_ID Path segment after shorts VIDEO_ID
https://www.youtube.com/embed/VIDEO_ID Path segment after embed VIDEO_ID

For a fixed, known video, copy the ID into the thumbnail URL. For user-submitted URLs, parse the URL instead of concatenating untrusted input directly into HTML.

2. Use a direct thumbnail URL

The commonly used pattern is https://i.ytimg.com/vi/{videoid}/{size}.jpg. Conventional size suffixes include default, mqdefault, hqdefault, sddefault, and maxresdefault. Availability varies by video, so do not assume every suffix exists.

A video ID becomes a thumbnail URL that the browser renders as an image.
A video ID becomes a thumbnail URL that the browser renders as an image.
<figure class="video-card">
  <a href="https://www.youtube.com/watch?v=VIDEO_ID">
    <img
      src="https://i.ytimg.com/vi/VIDEO_ID/hqdefault.jpg"
      alt="Watch the video"
      width="480"
      height="360"
      loading="lazy"
      decoding="async"
    >
  </a>
  <figcaption>Watch the video on YouTube</figcaption>
</figure>

Choosing a suffix

Suffix Typical use Caveat
default Small fallback card Lowest conventional resolution
mqdefault Compact lists Availability can vary
hqdefault General-purpose cards Commonly used, not an availability guarantee
sddefault Larger previews Not present for every video
maxresdefault Large hero image Often unavailable for some videos

The direct suffix conventions are documented by the lite-youtube-embed implementation reference, while Google’s API documentation is the authoritative source for thumbnail objects returned by the API. Treat direct URL availability as an implementation caveat rather than a public API contract.

3. Parse a video URL safely in JavaScript

This browser function handles watch, short, Shorts, and embed URLs. It returns null for an unsupported URL.

function getYouTubeVideoId(input) {
  let url;
  try {
    url = new URL(input);
  } catch {
    return null;
  }

  const host = url.hostname.toLowerCase().replace(/^www\\./, '');

  if (host === 'youtu.be') {
    return url.pathname.split('/').filter(Boolean)[0] || null;
  }

  if (host === 'youtube.com' || host === 'm.youtube.com') {
    if (url.pathname === '/watch') return url.searchParams.get('v');
    const parts = url.pathname.split('/').filter(Boolean);
    if (parts.length === 2 && ['shorts', 'embed', 'live'].includes(parts[0])) {
      return parts[1];
    }
  }

  return null;
}

function thumbnailUrl(videoUrl, size = 'hqdefault') {
  const id = getYouTubeVideoId(videoUrl);
  if (!id) throw new Error('Unsupported YouTube URL');
  return `https://i.ytimg.com/vi/${encodeURIComponent(id)}/${size}.jpg`;
}

const src = thumbnailUrl('https://www.youtube.com/watch?v=VIDEO_ID');
const image = document.querySelector('#thumbnail');
image.src = src;
image.alt = 'YouTube video thumbnail';

Set the alt text to describe the destination or subject. If the image is purely decorative beside a visible title, use an empty alt value. Add explicit dimensions or an aspect-ratio rule to reduce layout shift.

4. Get the returned thumbnail URL with the YouTube Data API

Use videos.list with part=snippet and the video ID, then read a URL from the returned snippet.thumbnails object. The API response includes the URL, width, and height for each available size.

async function getThumbnailFromYouTubeApi(videoId, apiKey) {
  const params = new URLSearchParams({
    part: 'snippet',
    id: videoId,
    key: apiKey
  });

  const response = await fetch(`https://www.googleapis.com/youtube/v3/videos?${params}`);
  if (!response.ok) {
    throw new Error(`YouTube API request failed: ${response.status}`);
  }

  const data = await response.json();
  const video = data.items?.[0];
  if (!video) throw new Error('Video was not found or is unavailable');

  const thumbnails = video.snippet?.thumbnails || {};
  const selected = thumbnails.maxres || thumbnails.standard || thumbnails.high ||
    thumbnails.medium || thumbnails.default;

  if (!selected?.url) throw new Error('The response contained no thumbnail URL');
  return selected;
}

getThumbnailFromYouTubeApi('VIDEO_ID', 'YOUR_API_KEY')
  .then(({ url, width, height }) => {
    const image = document.querySelector('#thumbnail');
    image.src = url;
    image.width = width;
    image.height = height;
  })
  .catch(console.error);

Google documents these usual dimensions: default 120×90, medium 320×180, high 480×360, standard 640×480, and maxres 1280×720. Some resources also expose fhd, qhd, or uhd. Use the dimensions in the response instead of assuming a fixed ratio.

Direct URL versus API lookup

Need Best fit
One known video and minimal setup Construct the direct URL
A reliable available-size fallback Use videos.list and select a returned object
Server-side catalog or CMS integration Store the API-returned URL and dimensions
Stable SEO metadata across systems Choose one accessible URL and reuse it consistently

5. Add responsive, accessible HTML

<picture>
  <img
    src="https://i.ytimg.com/vi/VIDEO_ID/hqdefault.jpg"
    alt="Description of the video"
    width="480"
    height="360"
    loading="lazy"
    decoding="async"
    style="width:100%;height:auto;object-fit:cover;"
  >
</picture>

Direct YouTube thumbnail variants can have different aspect ratios. If every card must have the same shape, define the box deliberately:

.video-card {
  aspect-ratio: 16 / 9;
  overflow: hidden;
}

.video-card img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

Cropping with object-fit: cover changes what is visible; use contain when preserving the complete image matters.

6. Thumbnail versus playable embed

An image is only a preview. To play the video, add a YouTube iframe separately, usually after a click or with a lazy embed component.

<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/VIDEO_ID"
  title="YouTube video player"
  loading="lazy"
  allowfullscreen
></iframe>

Do not describe a thumbnail as a player. A linked image is useful for a lightweight card, while the iframe loads the playback experience.

7. SEO and social metadata

Google Search Central recommends a single unique, stable thumbnail URL for each video and says the image must be accessible to Googlebot and Googlebot Images. Depending on your implementation, the thumbnail can be referenced by the HTML video poster attribute, VideoObject.thumbnailUrl, a video sitemap’s thumbnail_loc, or Open Graph og:video:image. Keep the URL consistent when using more than one method.

<meta property="og:video:image" content="https://i.ytimg.com/vi/VIDEO_ID/hqdefault.jpg">

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "VideoObject",
  "name": "Video title",
  "thumbnailUrl": ["https://i.ytimg.com/vi/VIDEO_ID/hqdefault.jpg"],
  "embedUrl": "https://www.youtube.com/embed/VIDEO_ID"
}
</script>

Search features have additional eligibility criteria; adding metadata does not guarantee a video result. See Google’s video SEO guidance and the YouTube video resource documentation.

8. Edge cases and fallback handling

  • Missing large variant: try a smaller suffix or use the API response’s available object.
  • Private, removed, or unavailable video: the API may return no item; show a local placeholder and keep the video link out of the card.
  • Unexpected aspect ratio: read the API width and height, or use CSS cropping intentionally.
  • Untrusted input: parse with URL, allow only YouTube hosts, and escape values before inserting HTML.
  • Observed 404 behavior: the lite-youtube-embed reference reports that some thumbnail requests returning 404 may still carry JPEG data. Because this is a third-party observation, test the actual response and do not rely on img.onerror alone as a universal missing-image check.

9. Troubleshooting

Symptom Likely cause Fix
Broken image The selected suffix is unavailable Try hqdefault or select a URL returned by snippet.thumbnails.
Image shows but is distorted Forced width and height do not match the source ratio Use the returned dimensions or set height:auto.
Wrong video The ID was copied from the wrong URL part Parse v, youtu.be, shorts, or embed explicitly.
API returns an empty item list The video is unavailable or the ID is invalid Check the ID and render a fallback state.
API request fails Request parameters or project credentials are incorrect Check the official videos.list documentation and inspect the HTTP status and response body.
Thumbnail is not indexed Googlebot cannot access the image or metadata is inconsistent Use one stable, publicly accessible URL across page metadata.
Page shifts while loading No intrinsic image dimensions Provide width and height, or reserve space with CSS.

10. Performance, reliability, and cost considerations

  • Use loading="lazy" for thumbnails below the fold and decoding="async" for non-blocking decoding.
  • Do not call the Data API for every render if the video ID and thumbnail URL can be cached in your database or application cache.
  • Use direct URLs for simple pages, but retain an API-returned fallback when missing-size handling matters.
  • Reserve layout space with dimensions or aspect-ratio to reduce cumulative layout movement.
  • Keep the thumbnail separate from the player so a card does not load an iframe until the visitor asks to play.
  • Do not assume a particular API quota, price, or authorization configuration without checking your current Google project documentation.

11. Or skip the browser setup

If your goal is to capture the finished page that contains the thumbnail, ScreenshotNeo can return a PNG, JPEG, WebP, or PDF from one request. Its capture options include full-page screenshots, custom CSS and JavaScript, waiting for a selector or network idle, and device or viewport settings.

A clean capture removes obstructing overlays before rendering the final image.
A clean capture removes obstructing overlays before rendering the final image.

See the ScreenshotNeo API documentation for all options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://screenshotneo.com/blog/ -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://screenshotneo.com/blog/"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://screenshotneo.com/blog/' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. ScreenshotNeo also provides an MCP server so Claude, Cursor, and other AI agents can take screenshots. The Free plan includes 1,000 screenshots each month with no card, and paid plans start at $5 for 3,000 shots.

Sign up for 1,000 free screenshots a month.

FAQ

Can I use a YouTube thumbnail without an API key?

Yes. For a known video, construct the i.ytimg.com URL directly. Use the Data API when you need returned availability and dimensions.

Does the thumbnail URL play the video?

No. It returns a still image. Use a YouTube iframe or a link to the watch page for playback.

Which thumbnail size should I choose?

Start with hqdefault for a general card. For guaranteed knowledge of an available variant, select from the API’s returned snippet.thumbnails objects.

Can I use the thumbnail in structured data?

Yes. Google documents VideoObject.thumbnailUrl, HTML video poster, video sitemaps, and Open Graph video image metadata. Use one stable, accessible URL consistently.

Why does a thumbnail sometimes have a different shape?

YouTube exposes multiple thumbnail dimensions and ratios. Read the API’s width and height or apply deliberate CSS with object-fit.

Should I screenshot a YouTube page or fetch its thumbnail URL?

Fetch the thumbnail URL when you only need the image. Use a screenshot service when you need a rendered page, a full-page capture, a PDF, or controlled browser actions around the thumbnail.