Create a Dashboard with Next.js API Routes - YouTube API

LR

Lee Robinson / February 05, 2020

4 min read––– views

In this series, you will learn how to create a dashboard using Next.js API routes and integrate with third-party APIs.

YouTube Subscribers

-

Overview#

YouTube has cemented itself as the number one video sharing platform. Its vibrant community of creators is growing exponentially.

Tracking metrics about your channel is an integral part of measuring your success. YouTube provides a Data API, which allows you to integrate the platform directly into your website. Since I'm a YouTube Creator, I wanted to see how many times my subscriber count and views directly on my site.

Getting Access to Youtube#

To gain access to the YouTube API, you need to:

  • Go to the Google Developer Console.
  • Create a new project.
  • Credentials -> Create Credentials -> Service-account key.
  • Click “Enable APIs and services.”
  • Find "YouTube Data API v3" and enable it.

Since we're communicating server-to-server, we'll need a service account.

  • Go to your service accounts page.
  • Create a service account.
  • Click "Create Key" and choose JSON.

You should now have a JSON file similar to this:

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}

We use this key later to set up our client in our API Route. Okay, back to the service account. We need to delegate domain-wide authority.

  • On the table row, click Actions -> Edit.
  • Show Domain-Wide Delegation -> Enable G-Suite Domain-Wide Delegation.

That's it! 🎉 You now have access to make requests to the YouTube API with your service account.

Creating an Environment Variable#

To securely access the API, we need to include the secret with each request. We also do not want to commit secrets to git. Thus, we should use an environment variable.

Since I'm deploying with Vercel, I can add the secrets via their CLI. We only need a few of the values from the JSON file. For the private key, make sure you convert the new line characters (\n) to actual new lines.

$ vc secret add -- google-private-key "-----BEGIN PRIVATE KEY-----
MIIEvQIBA
..
..
2DAVOW4c=
-----END PRIVATE KEY-----"
$ vc secret add google-client-email my-account@project.iam.gserviceaccount.com
$ vc secret add google-client-id 721877721877

To reference these values locally when using vc dev, they need to be added to your .env file.

GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nDVOW4c=\n-----END PRIVATE KEY-----\n"
GOOGLE_CLIENT_EMAIL=my-account@project.iam.gserviceaccount.com
GOOGLE_CLIENT_ID=721877721877

Finally, we need to add the secrets to our vercel.json.

vercel.json
{
  "env": {
    "GOOGLE_PRIVATE_KEY": "@google-private-key",
    "GOOGLE_CLIENT_EMAIL": "@google-client-email",
    "GOOGLE_CLIENT_ID": "@google-client-id"
  }
}

We can now reference the secrets via process.env.GOOGLE_PRIVATE_KEY in our API route.

Note: If you have a lot of environment variables in Vercel, you might need to encrpyt your service account.

Creating the API Route#

Let's start by creating a new API route at pages/api/youtube.js.

export default (req, res) => {
  return res.status(200).json({});
};

To make server-side requests to YouTube, we can install the googleapis library.

$ yarn add googleapis

Then, we can initialize googleapis inside our API route.

import { google } from 'googleapis';

let googleAuth;

export default async (_, res) => {
  googleAuth = new google.auth.GoogleAuth({
    credentials: {
      client_email: process.env.GOOGLE_CLIENT_EMAIL,
      client_id: process.env.GOOGLE_CLIENT_ID,
      private_key: process.env.GOOGLE_PRIVATE_KEY
    },
    scopes: ['https://www.googleapis.com/auth/youtube.readonly']
  });

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

  return res.status(200).json({});
};

Finally, we want to pull statistics for a given channel and return the total number of subscribers and views.

import { google } from 'googleapis';

let googleAuth;

export default async (_, res) => {
  googleAuth = new google.auth.GoogleAuth({
    credentials: {
      client_email: process.env.GOOGLE_CLIENT_EMAIL,
      client_id: process.env.GOOGLE_CLIENT_ID,
      private_key: process.env.GOOGLE_PRIVATE_KEY
    },
    scopes: ['https://www.googleapis.com/auth/youtube.readonly']
  });

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

  const response = await youtube.channels.list({
    id: 'UCZMli3czZnd1uoc1ShTouQw',
    part: 'statistics'
  });

  const channel = response.data.items[0];
  const { subscriberCount, viewCount } = channel.statistics;

  return res.status(200).json({
    subscriberCount,
    viewCount
  });
};

Example#

The two cards below talk to /api/youtube and pull back stats about my YouTube account.

Bonus: You can cache the API route with the cache-control header.

Cache-Control: public, max-age=120, stale-while-revalidate=60

Keep Reading#

Create a Dashboard with Next.js API Routes

Mastering Next.js

The premiere video course for building static and server-side rendered applications with Next.js and React.

jamstackfns

The best serverless functions for JAMstack applications. Deploy to Vercel or Netlify for your static site.

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.