CORS error on GET top games Twitch API

Hi Twitch developers community,

I am building react app to display the top games by calling Twitch API. So far in https://dev.twitch.tv/console

  1. I have registered my app in console given a name,
  2. I have my redirect URL set to : http://localhost
  3. I created my client secret

I am not using any server like Express.js, so there is no server-to-server use case here.
My current goal is to simply using Axios to invoke twitch API like top-games: https://api.twitch.tv/helix/games/top
and then render the payload on my dashboard

This is my code for creating Axio instance here:

    const api = axios.create({
       headers: {
         "client_id": "my client id",
         "client_secret": 'my client secret',
         "redirect_uri": 'http://localhost',
         "grant_type": "client_credentials"
  },
});

I am getting CORS error everytime when making the api call, the error message capture in console:

Access to XMLHttpRequest at 'https://api.twitch.tv/helix/games/top' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field grant_type is not allowed by Access-Control-Allow-Headers in preflight response.

What did I do wrong here ?Preformatted text

None of those headers you are sending are valid headers, which is why you’re getting an error that those headers are not allowed.

For making Helix API requests you need an OAuth token, and if you’re doing this from the client-side (as in, a browser) then you need to use the Implicit OAuth Flow https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-implicit-code-flow making sure to send those values as querystring params not headers.

Once you’ve got an access token, you can then make API requests. The Get Top Games example https://dev.twitch.tv/docs/api/reference#get-top-games shows what headers you should be sending, such as Client-ID, and Authorization.

@Dist
Thanks for quick reply. Question does this mean it will be a two steps procedure for making API request to twitch API ?

  1. make a call to https://id.twitch.tv/oauth2/authorize with required query parameter including
    client_id, redirect_uri, response_type, scope ?

     ?client_id=<your client ID>
     &redirect_uri=<your registered redirect URI>
     &response_type=<type>
     &scope=<space-separated list of scopes>
    
  2. Then using the returned access token from 1st call to make the request I want ?

For client-side requests you’ll use the Implicit auth flow, which means you need to actually send the user of your app there and if they approve your app they will be redirected back with an access token.

Once you have that access token you can make requests until that token expires, after which point you’ll need to send the user through the auth flow again.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.