Get Your Twitch Stream Live on Your Website

@lukeocodes 🕹👨‍💻 - Nov 16 '20 - - Dev Community

Is My Twitch Stream Live?

Ever wanted your Twitch live status on your own homepage? Well, we achieve that with a small Netlify function called from our site.

For the purposes of this post, let's assume credentials are always stored in environment variables...

Diving Right In™️

Get Twitch Credentials

Log into your Twitch account, head over your Developer Console applications and Register a New Application with Twitch.

Give the application a Name, OAuth Redirect URL, and Category.

Field Value Important?
Name My Twitch Stream Live? Not really
OAuth Redirect URL http://localhost:3000 Not really
Category Website Integration Not really

Yes, I mean it, none of these are really that important. The client credentials grant required for server-to-server authentication doesn't require a redirect URL, because it can validate the client ID and secret on the one leg.

Diagram of the Client Credentials Grant returning a token in a single request

Once you click Create, you'll be able to click on Manage for your new application. Here you'll find the Client ID, and generate a New Secret.

Add the Client ID and Client Secret to environment variables.

  • TWITCH_CLIENT_ID
  • TWITCH_CLIENT_SECRET

Create your Netlify Function

In your functions directory (we'll call ours functions/), create a new directory called live-on-twitch and change into it.

cd functions/
mkdir live-on-twitch
cd live-on-twitch/
Enter fullscreen mode Exit fullscreen mode

Initialise your npm application.

Now, add the basic structure of your function. It's not a very semantic endpoint, returning status: online or status: offline, and always a 200. 😇

exports.handler = async (event, context, callback) => {
  callback(null, {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ status: 'offline' }),
  })
}
Enter fullscreen mode Exit fullscreen mode

Launching http://localhost:55359/.netlify/functions/live-on-twitch, and making a request will return JSON. This URL is generated by netlify dev and may differ from what you see.

{
  "status": "offline"
}
Enter fullscreen mode Exit fullscreen mode

Request an App Access Tokens

Now, install axios, to make the requests with.

npm install axios
Enter fullscreen mode Exit fullscreen mode

Create the request options and then turn them into parameters for a post request to the Twitch OAuth service.

const qs = require('querystring')
const axios = require('axios')

exports.handler = async (event, context, callback) => {
  const opts = {
    client_id: process.env.TWITCH_CLIENT_ID,
    client_secret: process.env.TWITCH_CLIENT_SECRET,
    grant_type: 'client_credentials',
    scopes: '',
  }
  const params = qs.stringify(opts)

  const { data } = await axios.post(
    `https://id.twitch.tv/oauth2/token?${params}`
  )

  console.log(data)

  // callback
}
Enter fullscreen mode Exit fullscreen mode

Is Your Twitch Stream Live?

With the access_token returned from Twitch, now you can request the status of your stream.

// requires

exports.handler = async (event, context, callback) => {
  // get access_token

  const streamUser = 'vonagedevs'

  const {
    data: { data: streams },
  } = await axios.get(
    `https://api.twitch.tv/helix/streams?user_login=${streamUser}`,
    {
      headers: {
        'Client-ID': process.env.TWITCH_CLIENT_ID,
        Authorization: `Bearer ${data.access_token}`,
      },
    }
  )

  // callback
}
Enter fullscreen mode Exit fullscreen mode

Because you look for a single user_login from the streams endpoint, we'll assume a stream.length is online, as it will be zero if you're offline.

The Full Code

Here is the function in full.

const qs = require('querystring')
const axios = require('axios')

exports.handler = async (event, context, callback) => {
  const opts = {
    client_id: process.env.TWITCH_CLIENT_ID,
    client_secret: process.env.TWITCH_CLIENT_SECRET,
    grant_type: 'client_credentials',
    scopes: '',
  }
  const params = qs.stringify(opts)

  const { data } = await axios.post(
    `https://id.twitch.tv/oauth2/token?${params}`
  )

  const streamUser = 'vonagedevs'

  const {
    data: { data: streams },
  } = await axios.get(
    `https://api.twitch.tv/helix/streams?user_login=${streamUser}`,
    {
      headers: {
        'Client-ID': process.env.TWITCH_CLIENT_ID,
        Authorization: `Bearer ${data.access_token}`,
      },
    }
  )

  callback(null, {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ status: streams.length ? 'online' : 'offline' }),
  })
}
Enter fullscreen mode Exit fullscreen mode

What Did We Use It For?

If we're live on Twitch, we're going to enhance the landing page of our blog with the stream!

Our stream is live on our site when we're online

. . . . . . . . . . . . . . . . . . . . . . . . . . .