Home

Published

- 2 min read

Fixing the Issue with blocked iframes in NextJS

img of Fixing the Issue with blocked iframes in NextJS

I recently switched from GatsbyJS to NextJS. Instead of creating a site from scratch I decided to use the tailwind-nextjs-starter-blog as a starting point. The migration was straight forward, simply migrate the frontmatter block to the new format.

However one thing suddenly stopped working - Youtube Embed iFrames.

First Attempt: Convert iframe into a React Component

My first assumption was that maybe you are not suppose to embed iframes directly in your *.mdx files. In addition the first google hit for the issue was: The simplest way to embed a youtube video in your react app

The solution is very nice and also makes the video embed responsive. However it does not solve the ‘content blocked’ issue.

Deeper Analysis

By pressing F12 in the browser you can open the web developer tools.

Here we can see two separate issues:

  • An issue with the ‘Content Security Policy directive’
  • An issue with the property ‘allowfullscreen’ not written in the JSX style

Solution

For the property allowfullscreen we simply just have to rename the property to allowFullScreen to match the JSX style.

It turns out this theme I am using already has a very strict security policy to avoid clickjacking. This means you must explicitty define which external sites are allowed to be embedded.

You configure this in the file next.config.js. Here we need to adjust the ContentSecurityPolicy to allow the external site. In this case www.youtube.com.

// You might need to insert additional domains in script-src if you are using external services
const ContentSecurityPolicy = `
  default-src 'self';
  script-src 'self' 'unsafe-eval' 'unsafe-inline' giscus.app;
  style-src 'self' 'unsafe-inline';
  img-src * blob: data:;
  media-src 'none';
  connect-src *;
  font-src 'self';
  frame-src giscus.app www.youtube.com
  `