Generate Access Tokens

Learn to generate app access and user access tokens for the Twitch API.

Generate an app access token

With our client ID and secret, we finally have everything we need to generate our access tokens. Let's start with the app access token.

We'll use the OAuth client credential grant flow to get our app access token. In this grant flow, the server directly authorizes an application, rather than a user, by generating an access token for the application once it provides its client ID and secret.

The illustration below gives an overview of this grant flow.

To retrieve our access token, we need to send an HTTP POST request to the following URL:

https://id.twitch.tv/oauth2/token

Here are the query parameters we pass to this call:

Parameter

Type

Category

Description

client_id

String

Required

This is the registered client ID of an application created on the Twitch Developer Console.

client_secret

String

Required

This is the registered client secret of an application created on the Twitch Developer Console.

grant_type

String

Required

This is the type of grant flow we're using. Since we're using the client credential grant flow, the value of this parameter will be client_credentials.

If the POST request we make to this URL is successful, the server responds with a JSON object containing the following properties:

Property

Type

Description

access_token

String

This is the app access token generated from the request.

expires_in

Number

This is the time in seconds for which the generated token is valid.

token_type

String

This is the type of token generated from the request. Using the client credential grant flow, the type of token we get is bearer.

Let's make an actual request to retrieve our access token. The code to make the call has already been provided, and it automatically extracts the access token for us. Therefore, all we need to do is provide our client ID and secret. Let's do so by following the steps below:

  1. Click "Edit" in the widget below.

  2. Provide your client ID and secret in the CLIENT_ID and CLIENT_SECRET fields, respectively.

  3. Click "Run" to run the code.

  4. When the access token is generated and extracted, click "Save" to save the token for use throughout the course.

Note: As we mentioned earlier, the token will expire after a certain amount of time has passed, specified by the expires_in field. You can always return to this section if your access token expires and generate a new token.

Press + to interact
// Importing the required libraries
import fetch from "node-fetch";
// Defining the endpoint URL
const endpointUrl = new URL("https://id.twitch.tv/oauth2/token");
// Defining the request parameters
const queryParameters = new URLSearchParams({
client_id: "{{CLIENT_ID}}",
client_secret: "{{CLIENT_SECRET}}",
grant_type: "client_credentials",
});
// Setting API call options
const options = {
method: "POST",
};
// Function to make API call and fetch the app access token
async function fetchAccessToken() {
try {
endpointUrl.search = queryParameters;
const response = await fetch(endpointUrl, options);
printResponse(response);
} catch (error) {
printError(error);
}
}
// Calling function to fetch the access token
fetchAccessToken();

Generate a user access token

We've learned to generate the app access token. Let's turn our attention to user access tokens.

User access tokens come in handy when we want our application to access a user's resources. The OAuth grant flow we'll use for this access token is the implicit grant flow. In this flow, the server directly authorizes a client by providing an access token.

To retrieve a token using this flow, we need to enter the following URL in our browser:

https://id.twitch.tv/oauth2/authorize

Here are the query parameters we need to pass to this URL:

Parameter

Type

Category

Description

client_id

String

Required

This is the registered client ID of an application created on the Twitch Developer Console.

redirect_uri

String

Required

This is the URI to which the access token will be sent. It will be the URI we registered for the application that we created on the Twitch console.

response_type

String

Required

This is the type of response we expect from the server. Since we want an access token, the value of this parameter will be token.

scope

String

Required

This is a URL-encoded string of scopes that the application is allowed to access.

force_verify

Boolean

Optional

This shows whether the user will be forced to reverify the application's access to their resources. This may happen in case the application requests access to some resources repeatedly. Its default value is false.

state

String

Optional

This is a state string to prevent cross-site request forgery (CSRF) attacks.

To generate a user access token, we must have an application running on the URL we registered as an OAuth redirect URL for our application on the Twitch Developer Console. In our case, this URL is Educative's VM URL. Let's serve an application on this URL and make a token request by following the steps below:

  1. If you haven't already, provide your client ID in the CLIENT_ID field below.

  2. Run the React app below and click the link at the end of the widget to open the application in a new browser tab.

  3. Click the hyperlink displayed on the application. It will redirect you to Twitch.

  4. If you aren't already, log in to Twitch, and click "Authorize" to authorize our application to access the scopes we've defined.

  5. Once you're redirected to the React application, copy the access token displayed on the application. We can also find this token in the URL fragment, identified by the access_token key.

  6. Store the access token somewhere safe.

Note: Like the app access token, the user access token will also expire after a certain amount of time has passed. You can always return to this section if your access token expires and generate a new token.

import Token from "./Token"
import "./App.css"

function App() {
  // The URL to which we will make the request
  const baseUrl = "https://id.twitch.tv/oauth2/authorize";

  // Defining the parameters to be passed to the request
  const queryParams = {
    client_id: "{{CLIENT_ID}}",
    redirect_uri: "{{EDUCATIVE_LIVE_VM_URL}}",
    response_type: "token",
    scope: [
      "channel:read:editors",
      "channel:read:subscriptions",
      "channel:manage:broadcast",
      "channel:manage:schedule",
      "clips:edit",
      "user:read:blocked_users",
      "user:read:email",
      "user:read:follows",
      "user:manage:blocked_users",
      "user:edit",
    ],
  };

  return (
    <div>
      <h1>
        <center>Welcome to React!</center>
      </h1>
      <Token baseUrl={baseUrl} queryParams={queryParams} />
    </div>
  );
}

export default App;
Making an access token request through a React application

This token has all the scopes required to run all the endpoints discussed in this course, so we don't have to worry about generating a new token for each call.

Note: To learn more about scopes and what they define, visit this lesson.

Save the token

Let's save our newly generated user access token to use throughout the course. The code below saves the token and makes a test call to one of the Twitch API's endpoints to check whether the access token is valid.

Provide your user access token in the USER_ACCESS_TOKEN field below and run the code. This fetches the details of our account on Twitch.

Press + to interact
// Importing libraries here
import fetch from "node-fetch";
// Defining the endpoint URL
const endpointUrl = new URL("https://api.twitch.tv/helix/users");
// Defining the header parameters
const headerParameters = {
Authorization: "Bearer {{USER_ACCESS_TOKEN}}",
"Client-Id": "{{CLIENT_ID}}",
};
// Setting API call options
const options = {
method: "GET",
headers: headerParameters,
};
// Function to make API call and fetch our account details
async function fetchUserDetails() {
try {
const response = await fetch(endpointUrl, options);
printResponse(response);
} catch (error) {
printError(error);
}
}
// Calling function fetch account details
fetchUserDetails();

With our access tokens saved, we can finally start making calls to the numerous endpoints of the Twitch API.