How to Add Youtube Analytics API to Fetch Channel Statistcs and Videos with React NextJs



YouTube is more than just a platform to share videos; it's an endless source of information just waiting to be discovered.

Making use of YouTube data is much more than simply statistics; it's about knowing your audience's heartbeat. You can discover stuff that resonates by following metrics like views, likes, shares, and comments. These metrics act as breadcrumbs. Having such information at your disposal makes developing a successful channel strategy not only realistic but also easy.

By tapping into this API, you gain unprecedented access to audience behaviors and preferences. From popular videos to watching time trends, every data point shapes a narrative of viewer engagement.

With these insights, you will be able to customize your content strategy with precision, delivering the right message to the right audience at the right time.

The YouTube Analytics API isn't just a tool; it's your compass in the landscape of digital content creation, guiding you toward growth and community engagement.

Why YouTube Analytics API?

The YouTube Analytics API is your doorway to extensive video analytics via unique reports. It allows you to quickly evaluate the success of your channel and gain essential information for improving your content strategy.

In an era where simply uploading videos no longer guarantees visibility, YouTube content creation has evolved into a fiercely competitive arena. To stand out amidst the noise, a well-defined strategy is essential. By using the YouTube Analytics API, you equip yourself with the tools needed to not only attract but also engage relevant viewers, thus elevating your channel above the competition.

YouTube Analytics API vs. YouTube Data API

The YouTube Analytics API provides real-time snapshots of your channel's activity. It furnishes customized reports that can be sorted and filtered to meet specific needs, making it ideal for swift assessments and gaining a comprehensive understanding of video and channel performance.

Conversely, the Youtube Data API digs into various aspects of your channel, videos, subscriptions, playlists, and channel configurations. It allows for searches based on diverse parameters such as terms, topics, locations, and publication dates.

How to Discover Insights of Youtube Channels and Content with Youtube Analytics API with React NextJs

Follow the steps mentioned here to get significant insights of Youtube content and channels using the YouTube Analytics API with react nextJs.

Set up your Project on Google Cloud Console

Create a Project on Google Cloud Console. Go to the Google Cloud Console. Create a new project or select an existing project. 



Now switch to API Library.



Enable YouTube Analytics API

Search for the YouTube Analytics API for youtube api access and enable it like I did.



Set up OAuth Credentials

Now it's time to create credentials, as youtube api without oauth is not possible. 

Go to the credentials page, now create credentials by selecting OAuth Client ID.


Now, click on the "Configure consent screen".



On the OAuth consent screen, select "External" and click on "create".


Fill your App Information with the name of your application and support email.


Now "save and continue".



Now "save and continue" with all the consent scopes.



Add users by providing a valid email address.



And "save and continue" to proceed further.



Create an OAuth Client ID with application type and name.



Save your Client ID and Client Secret for further use.



Install Necessary Dependencies for your NextJs Project

In your Next.js project, install the required packages.

npm install googleapis next-auth

Set up NextAuth

Create an auth folder in the Pages folder and paste this code.

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorizationUrl: 'https://accounts.google.com/o/oauth2/auth?response_type=code&prompt=consent&access_type=offline&scope=https://www.googleapis.com/auth/youtube.readonly'
    })
  ],
  callbacks: {
    async jwt(token, account) {
      if (account) {
        token.accessToken = account.accessToken;
        token.refreshToken = account.refreshToken;
      }
      return token;
    },
    async session(session, token) {
      session.accessToken = token.accessToken;
      return session;
    }
  }
});


Fetch Youtube Data API

Create API routes in the pages/api directory to interact with the YouTube API Statistics:

import { google } from 'googleapis';
import { getSession } from 'next-auth/client';

export default async (req, res) => {
  const session = await getSession({ req });
  
  if (!session) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  const youtube = google.youtube({
    version: 'v3',
    auth: session.accessToken
  });

  try {
    const response = await youtube.channels.list({
      part: 'statistics',
      mine: true
    });

    res.status(200).json(response.data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

And also to display videos.

import { google } from 'googleapis';
import { getSession } from 'next-auth/client';

export default async (req, res) => {
  const session = await getSession({ req });

  if (!session) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  const youtube = google.youtube({
    version: 'v3',
    auth: session.accessToken
  });

  try {
    const response = await youtube.search.list({
      part: 'snippet',
      forMine: true,
      type: 'video',
      maxResults: 10
    });

    res.status(200).json(response.data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};


Create index.js


import { useSession, signIn, signOut } from 'next-auth/client';
import { useEffect, useState } from 'react';

export default function Home() {
  const [session, loading] = useSession();
  const [stats, setStats] = useState(null);
  const [videos, setVideos] = useState(null);

  useEffect(() => {
    if (session) {
      fetch('/api/youtube/stats')
        .then(res => res.json())
        .then(data => setStats(data));

      fetch('/api/youtube/videos')
        .then(res => res.json())
        .then(data => setVideos(data));
    }
  }, [session]);

  return (
    <div>
      {!session && (
        <>
          <h1>You are not signed in</h1>import { useSession, signIn, signOut } from 'next-auth/client';
import { useEffect, useState } from 'react';

export default function Home() {
  const [session, loading] = useSession();
  const [stats, setStats] = useState(null);
  const [videos, setVideos] = useState(null);

  useEffect(() => {
    if (session) {
      fetch('/api/youtube/stats')
        .then(res => res.json())
        .then(data => setStats(data));

      fetch('/api/youtube/videos')
        .then(res => res.json())
        .then(data => setVideos(data));
    }
  }, [session]);

  return (
    <div>
      {!session && (
        <>
          <h1>You are not signed in</h1>
          <button onClick={signIn}>Sign in</button>
        </>
      )}
      {session && (
        <>
          <h1>Welcome {session.user.name}</h1>
          <button onClick={signOut}>Sign out</button>

          <h2>Channel Statistics</h2>
          {stats && <pre>{JSON.stringify(stats, null, 2)}</pre>}

          <h2>My Videos</h2>
          {videos && <pre>{JSON.stringify(videos, null, 2)}</pre>}
        </>
      )}
    </div>
  );
}
          <button onClick={signIn}>Sign in</button>
        </>
      )}
      {session && (
        <>
          <h1>Welcome {session.user.name}</h1>
          <button onClick={signOut}>Sign out</button>

          <h2>Channel Statistics</h2>
          {stats && <pre>{JSON.stringify(stats, null, 2)}</pre>}

          <h2>My Videos</h2>
          {videos && <pre>{JSON.stringify(videos, null, 2)}</pre>}
        </>
      )}
    </div>
  );
}


Set up .env

GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
NEXTAUTH_URL=http://localhost:3000


Run your Application

npm run dev


And we are done✌

Frequently Asked Questions

1. What is the API limit for YouTube Analytics?

The youtube api for developers use is limited. Each Google Cloud project you start has a default restriction of 10,000 "units" each day. The term "cost" refers to API usage limitations rather than monetary costs. Using the API is free.

2. How to get YouTube data API?

To get access to the YouTube Data API:

  • Create a Google Cloud Platform project.
  • Enable the YouTube Data API v3 in the project.
  • Generate OAuth 2.0 credentials or an API key.
  • Set up authorization if using OAuth.
  • Start making requests to the API endpoints using the credentials or API key.

3. What is the difference between YouTube Data API and YouTube Analytics API?

YouTube Data API provides access to YouTube's content, such as videos, playlists, and channels. YouTube Analytics API focuses on channel and video analytics, offering insights into performance metrics like views and engagement.

4. How to increase YouTube API limit?

To increase YouTube API limits:

  • 1. Apply for higher quota limits via the Google Cloud Console.
  • 2. Provide justification for increased usage.
  • 3. Await approval from Google.

5. What is youtube iframe api?


YouTube's iFrame API is a JavaScript toolkit that enables developers to embed YouTube videos on web sites and interact with them dynamically. It includes methods and events for managing video playing, retrieving youtube api to get video details, and modifying the appearance and behavior of embedded YouTube players.

6. What is youtube data api?


The YouTube Data API is a set of APIs supplied by YouTube that allow developers to access and interact with YouTube's massive collection of videos, channels, playlists, and other resources.

7. What is my youtube api key?


  • Go to the Google Developers Console
  • Create a new project
  • Enable the YouTube Data API
  • Create credentials
  • Get API Key

8. How to increase youtube api quota?


  • Sign in to Google Cloud Console
  • Select your project
  • Navigate to the Quotas page
  • Select YouTube Data API
  • Request quota increase
  • Submit your request

9. How youtube api works?


The YouTube API, especially the YouTube Data API, works by providing a collection of endpoints with which developers can interact via HTTP queries. These APIs enable developers to get, create, edit, and remove a wide range of data relating to YouTube videos, channels, playlists, comments, and more.

10. Can i use youtube api for free?


Yes, youtube api cost is free.

codegirl

Hello, I’m Sangita, person behind "codegirl", a dedicated web developer. Crafting digital experiences is not just my job; it’s my passion. Let’s build something exceptional together!

Post a Comment

Previous Post Next Post