How to Add a YouTube Playlist to a Next.js React App with the YouTube API

If you‘re a content creator on YouTube, you‘ve probably amassed an impressive collection of videos over time. But did you know you can showcase your video content outside of YouTube as well? By leveraging the power of the YouTube API, developers can easily integrate YouTube playlists and videos into their own websites and apps.

In this tutorial, I‘ll show you how to add a gallery of YouTube playlist videos to a Next.js React application. We‘ll fetch the playlist data from the YouTube API and display the videos in a responsive grid layout. Whether you want to feature your latest uploads, create a portfolio of your best work, or curate playlists around certain topics, this is a great way to extend the reach of your YouTube channel.

Let‘s get started!

What is the YouTube API?

The YouTube API allows developers to incorporate YouTube functionality and data into their own applications. With the API, you can perform actions like:

  • Search for videos, channels and playlists
  • Retrieve info about specific videos, channels and playlists
  • Manage your YouTube account (upload videos, modify playlists, etc.)
  • Embed and control video playback
  • Access viewer reports and analytics

YouTube offers a few different APIs depending on your use case. For this tutorial, we‘ll be working with the YouTube Data API, which lets us retrieve info about YouTube content.

The YouTube API uses RESTful architecture, allowing us to make simple HTTPS requests to retrieve or manipulate data in JSON format. To use the API, you‘ll need to create a Google Developer Console project and obtain credentials like an API key. Don‘t worry, I‘ll walk you through the process below.

Why add a YouTube playlist to your site?

There are a number of reasons you might want to display a YouTube playlist outside of YouTube:

  • You run a YouTube channel for your business/brand and want to showcase your video content on your official website
  • You‘re a content creator who wants a video portfolio page to share your best work
  • You‘re building an e-learning platform and want to curate playlists of educational videos on various topics
  • You want to embed relevant playlists to complement your blog posts or articles

Featuring YouTube playlists on your own site or app helps drive more views and engagement with your video content. It‘s an opportunity to reach people who may not be active on YouTube itself. An embedded playlist also encourages visitors to browse through multiple videos, increasing their time spent on your site.

From a development perspective, the YouTube API makes it straightforward to pull in playlist data and display it however you‘d like. You get full control over the design and user experience. And with a framework like Next.js, you can build a modern, performant React app that fetches the YouTube data at runtime.

Now that we understand the value proposition, let‘s dive into the code!

Setting up a Next.js project

First, make sure you have Node.js installed on your machine. If you don‘t already have it, you can download an installer from the official Node.js website.

With Node.js installed, open your terminal and navigate to the directory where you keep your development projects. To bootstrap a new Next.js app, run one of the following commands:

npx create-next-app@latest my-youtube-playlist
# or
yarn create next-app my-youtube-playlist

This will kick off an interactive setup process for your new project. Feel free to configure it however you‘d like or stick with the default options. After the dependencies finish installing, navigate into your project directory:

cd my-youtube-playlist

Next, start up the development server with:

npm run dev
# or
yarn dev

Now if you visit http://localhost:3000 in your browser, you should see the default Next.js starter page. We‘re ready to start building!

Creating a Google Developer Console project

Using the YouTube API requires a Google Developer Console project with the YouTube Data API enabled. Let‘s set that up now.

Head over to the Google Developer Console and sign in with your Google account. Then click the dropdown in the top left corner and select "New Project".

[Screenshot of creating a new Google Developer Console project]

Give your new project a name like "My YouTube Playlist". You can leave the Location set to "No organization". Click "Create" to spin up the new project.

After a few moments, you‘ll be dropped into the dashboard for your new project. In the left sidebar, go to "APIs & Services", then select "Library".

[Screenshot of the APIs & Services > Library page]

Search for "youtube" in the API library and select the "YouTube Data API v3" from the results. On the API page, click the "Enable" button.

[Screenshot of the YouTube Data API page]

Once the API is enabled, go to the "Credentials" page in the left sidebar. Click the "Create Credentials" button and select "API key".

[Screenshot of creating an API key credential]

This will generate an API key you can use to authenticate your requests to the YouTube API. Copy this key and store it somewhere secure for now.

Important: Treat this API key like a password and never expose it publicly. If you accidentally share it or commit it to version control, anyone could use it to make API requests that count against your quota.

Fetching playlist data with getServerSideProps

Now that we‘ve set up a Google Developer Console project and obtained an API key, we‘re ready to fetch some YouTube data! We‘ll use Next.js‘ getServerSideProps function to retrieve the data server-side at runtime.

Open up /pages/index.js in your project and add the following code above your Home component:

const YOUTUBE_PLAYLIST_ITEMS_API = ‘https://www.googleapis.com/youtube/v3/playlistItems‘;

export async function getServerSideProps() {
  const res = await fetch(`${YOUTUBE_PLAYLIST_ITEMS_API}?part=snippet&maxResults=50&playlistId=${process.env.YOUTUBE_PLAYLIST_ID}&key=${process.env.YOUTUBE_API_KEY}`)
  const data = await res.json();
  return {
    props: {
      data
    }
  }
}

Let‘s break this down:

  • We define a constant with the base URL for the YouTube playlistItems endpoint. This is the specific API endpoint we‘ll be using to fetch playlist details.

  • We define an async function called getServerSideProps. This is a special Next.js function that runs on the server-side before the page is rendered. Any data returned from this function will be passed as props to the page component.

  • In the function, we use the Fetch API to make a request to the playlistItems endpoint. We pass a few query parameters:

    • part=snippet specifies that we want to retrieve the snippet (title, description, thumbnails, etc) for each playlist item
    • maxResults=50 caps the number of results at 50. Adjust this as needed.
    • playlistId is the unique ID of the YouTube playlist we want to fetch. We‘ll pull this from an environment variable.
    • key is our API key, also pulled from an environment variable. This authenticates the request.
  • We await the response, parse the JSON data, and return it in an object under the props key. This data will now be available in the Home component via a data prop.

To provide our YouTube API key and playlist ID, create a file called .env.local in the root of your project with the following variables defined:

YOUTUBE_API_KEY=your_api_key_here
YOUTUBE_PLAYLIST_ID=your_playlist_id_here

Replace your_api_key_here with the API key from your Google Developer Console project. To find the ID of the playlist you want to use, go to the playlist page on YouTube and copy the value of the list query param in the URL.

Important: Add .env.local to your .gitignore file to avoid committing your API key.

With the environment variables in place, restart your development server to pick up the changes. If you log out the data prop in your Home component, you should now see the playlist data coming through!

Displaying the playlist on the page

We‘ve successfully retrieved the playlist data from the API. The last step is to loop through the videos and display them on the page.

In /pages/index.js, update the Home component to destructure the data prop and render a grid of playlist items:

export default function Home({ data }) {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>
          My YouTube Playlist
        </h1>

        <ul className={styles.grid}>
          {data.items.map(({ id, snippet = {} }) => {
            const { title, thumbnails = {}, resourceId = {} } = snippet;
            const { medium } = thumbnails;
            return (
              <li key={id} className={styles.card}>
                <a href={`https://www.youtube.com/watch?v=${resourceId.videoId}`}>
                  <p>
                    <img width={medium.width} height={medium.height} src={medium.url} alt="" />
                  </p>
                  <h3>{ title }</h3>
                </a>
              </li>
            )
          })}
        </ul>
      </main>
    </div>
  )
}

This code does the following:

  • Destructures the data prop passed in from getServerSideProps
  • Renders a heading for the playlist
  • Maps through the items array in the playlist data to render a card for each video
  • For each video item, destructures the relevant info from the snippet object (title, thumbnails, video ID)
  • Renders an <li> with an <a> link to the YouTube watch page for this video
  • Displays the thumbnail image and video title in the card

To get the layout looking nice, update the .grid class in /styles/Home.module.css with the following:

.grid {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  max-width: 1200px;
  list-style: none;
  padding: 0;
  margin: 0;
}

.grid img {
  max-width: 100%; 
}

This CSS accomplishes the following:

  • Sets the grid to use Flexbox for layout with wrapping enabled
  • Centers the grid both horizontally and vertically
  • Removes default list styles like bullets
  • Ensures the thumbnail images don‘t overflow their containers

Feel free to further customize the styles to your liking. You could enhance the hover state of the cards, apply a fancier font to the title, etc.

With these changes in place, you should see a nicely formatted grid of playlist video cards when you reload the page!

[Screenshot of YouTube playlist grid]

And that‘s it! We now have a Next.js app that fetches a YouTube playlist and renders the videos on the page. The CSS Modules keep things tidy with scoped class names, while getServerSideProps allows us to fetch data on the server at runtime.

Taking it further

Displaying a playlist is a great start, but there are tons of possibilities for what you can build with the YouTube API. Here are a few additional ideas to extend this project:

  • Add a search box that lets users dynamically filter the displayed videos by title
  • Create a dedicated watch page where you can embed a YouTube player and let users view the videos directly on your site
  • Add "Previous" and "Next" buttons to let users page through the playlist
  • Display additional metadata about each video like the view count, like count, and comment count
  • Integrate the YouTube Analytics API to show more advanced stats about your channel and videos
  • Build a control panel that lets you manage your YouTube channel (upload videos, modify playlists, etc.) from your own app

The YouTube API has a ton of endpoints to help you build all sorts of YouTube-powered features. I encourage you to check out the documentation to see what else you can create!

Wrapping up

In this tutorial, we walked through the process of integrating a YouTube playlist into a Next.js React app.

We started by setting up a new Next.js project and creating a Google Developer Console project to access the YouTube API. After obtaining an API key, we used the getServerSideProps function to fetch playlist data and pass it to our React component. Finally, we looped through the playlist items and rendered them in a grid on the page.

This approach provides an intuitive way to showcase your YouTube content within your own website or app. You can customize the design to match your branding and create a seamless experience for your audience.

By harnessing the power of the YouTube API and modern tooling like Next.js, React, and CSS Modules, you can build all sorts of rich video experiences. I hope this tutorial has inspired you to think creatively about how you can make the most of your YouTube content across platforms.

Now go forth and build something amazing!

Similar Posts