How to add Youtube to Headless CMS
Storyblok is the first headless CMS that works for developers & marketers alike.
In this article, we will learn how to add youtube to your headless CMS setup. We will use Storyblok to display how to do this. We will also create a custom field type we will prepare for you.
Component setup
Now, we will create a Youtube component to handle youtube content. Click the Add block {1} button on the right sidebar to create a new component.
Type in Youtube {1} since we do not have an existing Youtube component. You’ll see a Create new "Youtube" {2} with which you can add the new component under the input. When you click on that button, you’d see a search bar that allows us to search for an existing component or add a new one.
You’ll be prompted to define the component’s (Youtube) schema on adding the component. Schema is the properties of a component, and since we want to show videos with the Youtube component.
we should have a property of type Text {1} that holds the video URL, so let’s add a property video
.
To do this, enter the property name in the input and click the Add {2} button on the right-hand side.
On adding that property, you should see the property under the General tab, as shown in the image below.
Click on the Youtube component, copy and paste a youtube video URL in that field and click on Save {1} at the top left of the page.
We have to fetch the Youtube
component on the frontend of our app, get the video URL, and embed it in an iframe.
Showing the Youtube Video
They are many ways to fetch your Storyblok space content. In this tutorial, I will use the @Storyblok/js npm package.
- First, let’s fetch the space:
Above we fetched stories on home
page and checked for the Youtube
component. Then we wrote a function to split the URL and get the videoID
because youtube embed URL is different from the usual video URL.
- With the video ID, we can now play the video using an iframe: