A GDPR-Compliant YouTube Embed
An Astro component that loads YouTube only after a click: show once, agree and remember, or just the link. No cookie, no request to Google before consent.
Reviewed by adrian
on
I wanted to embed a YouTube video in a post on my old site. The usual <iframe src="youtube.com/embed/…"> opens a line to Google before the reader has clicked anything: cookies, fingerprint, IP address, all without consent. A textbook GDPR violation.
What I needed:
- No request to Google before the click. No thumbnail, no script, nothing.
- Real consent. The click on the button is the consent (Art. 6(1)(a) GDPR).
- Choices: show once, agree and remember, or just the link. No cookie, at most a
localStorageentry for the decision.
The result was a small Astro component with a pattern I had seen on zeit.de.
The component
src/components/YouTubeEmbed.astro:
---
import { getLocaleFromUrl, t } from '~/i18n/ui';
interface Props { id: string; title?: string }
const { id, title } = Astro.props;
const locale = getLocaleFromUrl(Astro.url);
const privacyHref = locale === 'de' ? '/datenschutz/' : '/en/privacy-policy/';
const youtubeUrl = `https://www.youtube.com/watch?v=${id}`;
---
<figure class="youtube-embed">
<div class="yt-consent" data-id={id} data-title={title ?? ''}>
<h3>{t(locale, 'youtube.externalContent')}</h3>
<p>{t(locale, 'youtube.description')}</p>
<p>
{t(locale, 'youtube.serviceName')}
{title && <><br /><strong>{title}</strong></>}
</p>
<div class="yt-consent-buttons">
<button type="button" data-remember="true">{t(locale, 'youtube.loadVideoRemember')}</button>
<button type="button">{t(locale, 'youtube.loadVideo')}</button>
<a href={youtubeUrl} target="_blank" rel="noopener noreferrer">{t(locale, 'youtube.watchOnYouTube')}</a>
</div>
<p class="footer">
{t(locale, 'youtube.consentFooter')}
<a href={privacyHref}>{t(locale, 'youtube.privacyLink')}</a>.
</p>
</div>
</figure>
A small script swaps the placeholder for an <iframe> on youtube-nocookie.com when a button is clicked:
<script>
const CONSENT_KEY = 'yt-consent';
function buildIframe(id, title, autoplay) {
const iframe = document.createElement('iframe');
iframe.src = `https://www.youtube-nocookie.com/embed/${id}?rel=0${autoplay ? '&autoplay=1' : ''}`;
iframe.allow = 'autoplay; encrypted-media; picture-in-picture; fullscreen';
iframe.allowFullscreen = true;
iframe.loading = 'lazy';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
if (title) iframe.title = title;
return iframe;
}
const hasConsent = (() => {
try { return localStorage.getItem(CONSENT_KEY) === '1'; } catch { return false; }
})();
document.querySelectorAll('.yt-consent').forEach((container) => {
const { id, title } = container.dataset;
if (!id) return;
if (hasConsent) {
container.replaceWith(buildIframe(id, title, false));
return;
}
container.querySelectorAll('button').forEach((button) => {
button.addEventListener('click', () => {
if (button.dataset.remember === 'true') {
try { localStorage.setItem(CONSENT_KEY, '1'); } catch {}
}
container.replaceWith(buildIframe(id, title, true));
});
});
});
</script>
Three details:
youtube-nocookie.cominstead ofyoutube.com, the privacy-enhanced mode. It only stores data on playback and sets no personalisation cookies.localStorageinstead of a cookie. The decision stays in the browser and is never sent to a server. Under ePrivacy rules this counts as strictly necessary, because it stores the consent itself and no tracking.- Direct replacement when consent exists. Whoever clicked "remember" sees the iframe straight away on later visits, but without
autoplay. Nobody likes videos that start on their own.
Texts in two languages
The strings sit in src/i18n/ui.ts, one set per locale:
'youtube.externalContent': 'External content',
'youtube.description': 'This is where you\'ll find external content from youtube.com that complements this article.',
'youtube.serviceName': 'YouTube video player (youtube.com)',
'youtube.loadVideo': 'Show once',
'youtube.loadVideoRemember': 'Agree and remember',
'youtube.watchOnYouTube': 'Watch on YouTube',
'youtube.consentFooter': 'I agree to external content being displayed. This may result in personal data being transmitted to third-party providers. More information in our',
'youtube.privacyLink': 'privacy policy',
getLocaleFromUrl(Astro.url) reads the language from the path, so German and English work without further code.
Adjusting the CSP
My strict CSP in Caddy blocked every external iframe, so the embed needed a targeted exception:
- frame-ancestors 'none';
+ frame-src https://www.youtube-nocookie.com; frame-ancestors 'none';
img-src needs no change, because the placeholder loads no images from Google. No thumbnail, no Google request before consent: that is the whole point of the construction.
Error 153 and the Referrer-Policy
The first test showed Error 153: Video player configuration error, even for videos that allow embedding.
The cause was my site-wide Referrer-Policy: no-referrer. YouTube checks the referrer to verify which domain the iframe comes from. No referrer, no verification, and a generic Error 153.
The fix is on the iframe: referrerPolicy = 'strict-origin-when-cross-origin'. YouTube then only sees https://adrian-altner.de without the path. An acceptable compromise, and verification works.
Privacy policy
I added a section "Video embeds (YouTube)" to the privacy policy. It describes the three choices and the localStorage entry yt-consent=1 (no cookie, local only, the consent decision only). It names Art. 6(1)(a) GDPR as the legal basis and the transfer to the US under standard contractual clauses. Today Google LLC is certified under the EU-US Data Privacy Framework.1
The demo
The post showed the component live with a cover of "Sweet Child O' Mine" by OZONE Band. Below it sat a callout box with the band's links and a Google Maps embed of Naka Weekend Market in Phuket. With the browser's network tab open, there was not a single request to google.com, ytimg.com or googlevideo.com before the click. After the click the iframe loaded, and only from youtube-nocookie.com.
Size
No consent library, no banner, no cookie. One component of about 100 lines of Astro, one script block, two CSP lines in Caddy and one section in the privacy policy. For the odd video on a blog, that was the right size between a full consent infrastructure and ignoring the problem.
Based on
-
Embedding YouTube videos GDPR-compliant: three-tier consent box without a cookie
(
raw/2026/2026-04-24/embedding-youtube-videos-gdpr-compliant-three-tier-consent-box-without-a-cookie.md) [post] - Google: Legal frameworks for data transfers [dpf]
Topic
- Static Website A website made of finished HTML files that are built once and then served unchanged. No server code, no database.
- Web Development How this site and others are made and found: static pages, search engines, the IndieWeb and maps in the browser.
Basis for
- A GDPR-Compliant Google Maps Embed An Astro component that loads Google Maps only after consent, stores the decision in localStorage and builds Google and Apple Maps links from coordinates.
Builds on
- Security Headers in Caddy A strict Content Security Policy, HSTS and no-referrer in a Caddy site block, checked with Webbkoll, securityheaders.com and the Mozilla Observatory.
Uses
- Astro Tool for building websites from content such as Markdown. Ships plain HTML by default and only loads JavaScript where it is needed.
- Caddy Web server and reverse proxy that obtains and renews TLS certificates on its own, configured in a short Caddyfile.
Mentioned in
- A Callout Component for Astro A reusable Astro info box with info, note and warning variants, an optional title, social links and a members section with links per person.