Generate Access Tokens
Learn to generate app access and user access tokens for the Twitch API.
We'll cover the following
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 |
| String | Required | This is the registered client ID of an application created on the Twitch Developer Console. |
| String | Required | This is the registered client secret of an application created on the Twitch Developer Console. |
| 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 |
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 |
| String | This is the app access token generated from the request. |
| Number | This is the time in seconds for which the generated token is valid. |
| String | This is the type of token generated from the request. Using the client credential grant flow, the type of token we get is |
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:
Click "Edit" in the widget below.
Provide your client ID and secret in the
CLIENT_ID
andCLIENT_SECRET
fields, respectively.Click "Run" to run the code.
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.
// Importing the required librariesimport fetch from "node-fetch";// Defining the endpoint URLconst endpointUrl = new URL("https://id.twitch.tv/oauth2/token");// Defining the request parametersconst queryParameters = new URLSearchParams({client_id: "{{CLIENT_ID}}",client_secret: "{{CLIENT_SECRET}}",grant_type: "client_credentials",});// Setting API call optionsconst options = {method: "POST",};// Function to make API call and fetch the app access tokenasync function fetchAccessToken() {try {endpointUrl.search = queryParameters;const response = await fetch(endpointUrl, options);printResponse(response);} catch (error) {printError(error);}}// Calling function to fetch the access tokenfetchAccessToken();
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 |
| String | Required | This is the registered client ID of an application created on the Twitch Developer Console. |
| 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. |
| 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 |
| String | Required | This is a URL-encoded string of scopes that the application is allowed to access. |
| 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 |
| 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:
If you haven't already, provide your client ID in the
CLIENT_ID
field below.Run the React app below and click the link at the end of the widget to open the application in a new browser tab.
Click the hyperlink displayed on the application. It will redirect you to Twitch.
If you aren't already, log in to Twitch, and click "Authorize" to authorize our application to access the scopes we've defined.
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.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;
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.
// Importing libraries hereimport fetch from "node-fetch";// Defining the endpoint URLconst endpointUrl = new URL("https://api.twitch.tv/helix/users");// Defining the header parametersconst headerParameters = {Authorization: "Bearer {{USER_ACCESS_TOKEN}}","Client-Id": "{{CLIENT_ID}}",};// Setting API call optionsconst options = {method: "GET",headers: headerParameters,};// Function to make API call and fetch our account detailsasync function fetchUserDetails() {try {const response = await fetch(endpointUrl, options);printResponse(response);} catch (error) {printError(error);}}// Calling function fetch account detailsfetchUserDetails();
With our access tokens saved, we can finally start making calls to the numerous endpoints of the Twitch API.