Twitch API Javascript example with source code

Connect to Twitch API using Javascript to get all live streams on the platform.

Share it on:

Twitch API Javascript example with source code

After this tutorial you will be able to read diffrent types of data from Twitch using their API in Javascript.

Sound good? Let's get started.

Setting up your Twitch application

Just like every major company API you need to create an application for each of your projects so they can authenticate you and track your usage.

Step #1. Sign In / Sign Up for a Twitch account.

Go to Twitch Developers and click on the Login in with Twitch button on the top right corner.

Step #2. Register your application.

After signing in you sholud be directed to the Console Page. Once you're there click on Register your application button.

Now, fill your application information (Name, OAuth Redirect URLs, Category).

Because we will use the Twitch API on our local machine here's how we would fill this information.

After you click create, Twitch might ask you to activate two factor authentication for your account.

If this happens to you, Go to your account settings -> security and privacy -> enable two-factor authentication.

Getting your Twitch application credentials

To connect to Twitch API you need two main things:

  1. Client ID: You can get your Client ID from Twitch developers application tab then click manage on your application.
  2. Client Secret: Click on New secret button to generate one.

Now that you have both Client ID and Client Secret, You can get your Authorization Object.

devsdash.com logo

Code Copied!

let clinetId = "CLIENT_ID_HERE";
let clinetSecret = "CLINET_SECRET_HERE";

function getTwitchAuthorization() {
    let url = `https://id.twitch.tv/oauth2/token?client_id=${clinetId}&client_secret=${clinetSecret}&grant_type=client_credentials`;

    fetch(url, {
    method: "POST",
    })
    .then((res) => res.json())
    .then((data) => handleAuthorization(data));
}

function handleAuthorization(data) {
    let { access_token, expires_in, token_type } = data;
    document.write(`${token_type} ${access_token}`);
}
getTwitchAuthorization();

When you place your Client ID and Client Secret in the code above, run the code and you will see similar result in your web browser:

Twitch API example in Javascript

Now that you have everything you need to connect, You can choose any endpoint to connect to.

There are a lot of diffrent endpoints you can connect to, for example (Get Clips, Get Top Games, Get Streams, etc).

However, for this example we're going to use the Get Streams endpoint.

You can view all diffrent endpoints from the Twitch API Reference.

The code below will request the Authorization Object then request all live streams and print the data on the browser as JSON.

devsdash.com logo

Code Copied!

let clinetId = "CLIENT_ID_HERE";
let clinetSecret = "CLINET_SECRET_HERE";

function getTwitchAuthorization() {
    let url = `https://id.twitch.tv/oauth2/token?client_id=${clinetId}&client_secret=${clinetSecret}&grant_type=client_credentials`;

    return fetch(url, {
    method: "POST",
    })
    .then((res) => res.json())
    .then((data) => {
        return data;
    });
}

async function getStreams() {
    const endpoint = "https://api.twitch.tv/helix/streams";

    let authorizationObject = await getTwitchAuthorization();
    let { access_token, expires_in, token_type } = authorizationObject;

    //token_type first letter must be uppercase    
    token_type =
    token_type.substring(0, 1).toUpperCase() +
    token_type.substring(1, token_type.length);

    let authorization = `${token_type} ${access_token}`;

    let headers = {
    authorization,
    "Client-Id": clinetId,
    };

    fetch(endpoint, {
    headers,
    })
    .then((res) => res.json())
    .then((data) => renderStreams(data));
}

function renderStreams(data) {
    document.body.innerHTML = `
${JSON.stringify(data)}
`; } getStreams();

When you run the code you will see similar result in your web browser: (Yours will appear as a big chunk of text)

And this is it, now you have all the live streams on Twitch in a JSON object and ready to be used.

As a bonus let's create a HTML page to present these data.

The code viewer below contains the final code of -> index.html, style.css and twitch.js.

devsdash.com logo

Code Copied!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Twitch Live Streams Example - DevsDash.com</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
        href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap"
        rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1>Twitch Live Streams</h1>
    <div class="streams"></div>
  </body>
  <script src="twitch.js"></script>
</html>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #fff;
  padding: 2rem;
}
h1 {
  text-align: center;
  color: #6441a5;
  font-size: 1.6rem;
  font-weight: 800;
}
.streams {
  width: 100%;
  margin-top: 3rem;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  column-gap: 1rem;
  row-gap: 2rem;
}
.stream-container {
  width: 100%;
  overflow: hidden;
  position: relative;
}
.stream-container::before {
  content: "LIVE";
  background-color: red;
  color: #ffffff;
  display: block;
  padding: 0.2rem 0.5rem;
  border-radius: 1rem;
  font-size: 0.8rem;
  position: absolute;
  top: 1rem;
  left: 1rem;
  z-index: 1;
  font-weight: 600;
}
.stream-container img {
  width: 100%;
  border-radius: 15px;
}
.stream-container h2 {
  font-size: 1rem;
  color: #000;
  line-height: 1.5;
  margin-top: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  display: -webkit-box;
  font-weight: 600;
  min-height: 3rem;
}
.stream-container p {
  margin-top: 1rem;
  font-size: 0.9rem;
  color: #6441a5;
  display: flex;
  align-items: center;
  font-weight: 600;
}
.stream-container p svg {
  margin-right: 0.5rem;
}
let clinetId = "CLIENT_ID_HERE";
let clinetSecret = "CLINET_SECRET_HERE";

function getTwitchAuthorization() {
    let url = `https://id.twitch.tv/oauth2/token?client_id=${clinetId}&client_secret=${clinetSecret}&grant_type=client_credentials`;

    return fetch(url, {
    method: "POST",
    })
    .then((res) => res.json())
    .then((data) => {
        return data;
    });
}

async function getStreams() {
    const endpoint = "https://api.twitch.tv/helix/streams";

    let authorizationObject = await getTwitchAuthorization();
    let { access_token, expires_in, token_type } = authorizationObject;

    token_type =
    token_type.substring(0, 1).toUpperCase() +
    token_type.substring(1, token_type.length);

    let authorization = `${token_type} ${access_token}`;

    let headers = {
    authorization,
    "Client-Id": clinetId,
    };

    fetch(endpoint, {
    headers,
    })
    .then((res) => res.json())
    .then((data) => renderStreams(data));
}

function renderStreams(data) {
    let { data: streams } = data;
    let streamsContainer = document.querySelector("div.streams");

    streams.forEach((stream) => {
    let { thumbnail_url: thumbnail, title, viewer_count } = stream;
    let hdThumbnail = thumbnail
        .replace("{width}", "1280")
        .replace("{height}", "720");
    streamsContainer.innerHTML += `
    
   <div class="stream-container">
        <img src="${hdThumbnail}" />
        <h2>${title}</h2>
        <p>
            <svg
            viewBox="0 0 15 15"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            width="15"
            height="15"
            >
            <path
                d="M.5 7.5l-.464-.186a.5.5 0 000 .372L.5 7.5zm14 0l.464.186a.5.5 0 000-.372L14.5 7.5zm-7 4.5c-2.314 0-3.939-1.152-5.003-2.334a9.368 9.368 0 01-1.449-2.164 5.065 5.065 0 01-.08-.18l-.004-.007v-.001L.5 7.5l-.464.186v.002l.003.004a2.107 2.107 0 00.026.063l.078.173a10.368 10.368 0 001.61 2.406C2.94 11.652 4.814 13 7.5 13v-1zm-7-4.5l.464.186.004-.008a2.62 2.62 0 01.08-.18 9.368 9.368 0 011.449-2.164C3.56 4.152 5.186 3 7.5 3V2C4.814 2 2.939 3.348 1.753 4.666a10.367 10.367 0 00-1.61 2.406 6.05 6.05 0 00-.104.236l-.002.004v.001H.035L.5 7.5zm7-4.5c2.314 0 3.939 1.152 5.003 2.334a9.37 9.37 0 011.449 2.164 4.705 4.705 0 01.08.18l.004.007v.001L14.5 7.5l.464-.186v-.002l-.003-.004a.656.656 0 00-.026-.063 9.094 9.094 0 00-.39-.773 10.365 10.365 0 00-1.298-1.806C12.06 3.348 10.186 2 7.5 2v1zm7 4.5a68.887 68.887 0 01-.464-.186l-.003.008-.015.035-.066.145a9.37 9.37 0 01-1.449 2.164C11.44 10.848 9.814 12 7.5 12v1c2.686 0 4.561-1.348 5.747-2.665a10.366 10.366 0 001.61-2.407 6.164 6.164 0 00.104-.236l.002-.004v-.001h.001L14.5 7.5zM7.5 9A1.5 1.5 0 016 7.5H5A2.5 2.5 0 007.5 10V9zM9 7.5A1.5 1.5 0 017.5 9v1A2.5 2.5 0 0010 7.5H9zM7.5 6A1.5 1.5 0 019 7.5h1A2.5 2.5 0 007.5 5v1zm0-1A2.5 2.5 0 005 7.5h1A1.5 1.5 0 017.5 6V5z"
                fill="currentColor"
            ></path>
            </svg>
            ${viewer_count
                .toString()
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",")} watching
        </p>
    </div>

    `;
    });
}

getStreams();

When you run the code you will see similar result in your web browser:

In This tutorial

  • Introduction