How to add Youtube to Headless CMS

Contents
    Try Storyblok

    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.

    What is Youtube?

    YouTube is an online video sharing and social media platform owned by Google, headquartered in San Bruno, California, and is the second most visited website after Google Search.

    Starting afresh

    Login to your Storyblok space, for the sake of the article, I’ll be creating a new space, but you can also do this in an existing space. After that, click on the Home entry.

    app.storyblok.com
    Storyblok Home component
    1

    Storyblok Home component

    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.

    app.storyblok.com
    Creating a new block for youtube
    1
    2

    Creating a new block for youtube

    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.

    app.storyblok.com
    Creating a field type for youtube block
    1
    2

    Creating a field type for youtube block

    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.

    Storyblok youtube component

    Storyblok youtube component

    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. 

    app.storyblok.com
    Storyblok Youtube component
    1

    Storyblok Youtube component

    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:

    import { StoryblokInit, apiPlugin } from "@Storyblok/js";
    
    const { StoryblokApi } = StoryblokInit({
      accessToken: [YOUR_ACCESS_TOKEN],
      use: [apiPlugin],
    });
    
      let videoId;
    
      const fetchStory = async () => {
        try {
          const { data } = await StoryblokApi.get("cdn/stories/home", {
            version: "draft",
          });
          const youtubeComponent = data?.story?.content?.body?.find(
            (item) => item.component === "Youtube"
          );
          const video_id = () => {
            if (
              youtubeComponent?.video?.startsWith(
                "https://www.youtube.com/watch?v="
              )
            ) {
              return youtubeComponent.video.split("=")[1];
            } else if (youtubeComponent?.video?.startsWith("https://youtu.be/")) {
              return youtubeComponent.video.split("/")[3];
            }
          };
          videoId = video_id;
        } catch (err) {
          console.log(err);
        }
      };
    
      fetchStory();

    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:

      <iframe
        width="100%"
        height="480"
        src={`https://www.youtube.com/embed/${videoId}`}
        title="YouTube video player"
        frameborder="0"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowfullscreen
      />



    Conclusion

    We’ve learned how to create a component for Youtube and how to fetch it and embed it into an iframe. We also saw that adding this component to a new or existing space is possible.