# Server to Server Endpoint request unauthorised

**URL:** <https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625>\
**Category:** API\
**Created:** [June 21, 2020, 6:28pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625 "2020-06-21T18:28:41Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![AdamJN](https://avatars.discourse-cdn.com/v4/letter/a/c89c15/32.png) [@AdamJN](https://discuss.dev.twitch.com/u/AdamJN)\
**Post date:** [June 21, 2020, 6:28pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/1 "2020-06-21T18:28:41Z")

</div>

Hi All,

Im creating a Analytics tool currently and I have managed to get my access token from the server and then validated it. Now im trying to make a request to the API but Im getting Unauthroized error in my console.

Im using JavaScrip on NodeJS to run the server.

```

async function RequestStreams() {
  got({
    url: "https://api.twitch.tv/helix/channels?broadcaster_id=44445592",
    method: "GET",
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer `+ accessToken
    },
    responseType: "json"
}).then(resp => {
  console.log("Ok", resp.body);
  if (resp.body.expires_in <= 3600) {
      twitch.makeClientCred();
  } else {
      // it"s ok
  }
}).catch(err => {
  console.log('Error Time!')
  console.error(err);
});
}

```

Above is the function im using to try and get a broadcasters channel but I have tried it with getting streams, channels and various other end points but get HTTPError: Response code 401 (Unauthorized) in the console.

Any help would be appreciated.

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [June 21, 2020, 6:31pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/2 "2020-06-21T18:31:15Z")

</div>

You need to not just read the HTTP Error code, but the Error/body message as well, as that covers what the problem is.

You are not sending a Client-ID Header and this is required

---

<div class="post-metadata">

**Author:** ![AdamJN](https://avatars.discourse-cdn.com/v4/letter/a/c89c15/32.png) [@AdamJN](https://discuss.dev.twitch.com/u/AdamJN)\
**Post date:** [June 21, 2020, 6:41pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/3 "2020-06-21T18:41:06Z")

</div>

Updated the code:

```

async function RequestStreams() {

  got({

    url: "https://api.twitch.tv/helix/streams/metadata",

    method: "GET",

    headers: {

        'Client-ID': TwitchClientID

    },

    responseType: "json"

}).then(resp => {

  console.log("Ok", resp.body);

  if (resp.body.expires_in <= 3600) {

      twitch.makeClientCred();

  } else {

      // it"s ok

  }

}).catch(err => {

  console.log('Error Time!')

  console.error(err);

});

}

```

And the Error I get is

```

Error Time!
HTTPError: Response code 404 (Not Found)
    at onResponse (D:\Twitch API Development\TwitchAppAnalytics\node_modules\got\dist\source\as-promise\index.js:124:28)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: undefined,
  timings: {
    start: 1592764794808,
    socket: 1592764794808,
    lookup: 1592764794808,
    connect: 1592764794817,
    secureConnect: 1592764794839,
    upload: 1592764794840,
    response: 1592764794989,
    end: 1592764794990,
    error: undefined,
    abort: undefined,
    phases: {
      wait: 0,
      dns: 0,
      tcp: 9,
      tls: 22,
      request: 1,
      firstByte: 149,
      download: 1,
      total: 182
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [June 21, 2020, 6:41pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/4 "2020-06-21T18:41:35Z")

</div>

You pasted the error message twice 😃

**Edit** after paste fixin, since I was super quick

```auto
    url: "https://api.twitch.tv/helix/streams/metadata",

    method: "GET",

    headers: {

        'Client-ID': TwitchClientID

    },

```

metadata is removed…

This doesn’t match your OP

```auto
async function RequestStreams() {
  got({
    url: "https://api.twitch.tv/helix/channels?broadcaster_id=44445592",
    method: "GET",
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer `+ accessToken
    },
    responseType: "json"
})

```

This

```auto
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer `+ accessToken
    },

```

becomes

```auto
    headers: {
        'Content-Type': 'application/json',
        'Client-ID': clientID,
        'Authorization': `Bearer `+ accessToken
    },

```

---

<div class="post-metadata">

**Author:** ![AdamJN](https://avatars.discourse-cdn.com/v4/letter/a/c89c15/32.png) [@AdamJN](https://discuss.dev.twitch.com/u/AdamJN)\
**Post date:** [June 21, 2020, 6:44pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/5 "2020-06-21T18:44:38Z")

</div>

Hi, Thanks for the help so far.

Im live working on the code while I was waiting for a reply. Here is the code with the changes.

```

async function RequestStreams() {

  got({

    url: "https://api.twitch.tv/helix/channels?broadcaster_id=44445592",

    method: "GET",

    headers: {

      'Content-Type': 'application/json',

      'Client-ID': TwitchClientID,

      'Authorization': `Bearer `+ accessToken

    },

    responseType: "json"

}).then(resp => {

  console.log("Ok", resp.body);

  if (resp.body.expires_in <= 3600) {

      twitch.makeClientCred();

  } else {

      // it"s ok

  }

}).catch(err => {

  console.log('Error Time!')

  console.error(err);

});

}

```

Still getting the same error though

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [June 21, 2020, 6:47pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/6 "2020-06-21T18:47:40Z")

</div>

Change

```auto
}).catch(err => {

  console.log('Error Time!')

  console.error(err);

});

```

To

```auto
}).catch(err => {

  console.log('Error Time!')

  console.error(err, err.response.body);

});

```

That should spit out the response body

---

<div class="post-metadata">

**Author:** ![AdamJN](https://avatars.discourse-cdn.com/v4/letter/a/c89c15/32.png) [@AdamJN](https://discuss.dev.twitch.com/u/AdamJN)\
**Post date:** [June 21, 2020, 6:52pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/7 "2020-06-21T18:52:52Z")

</div>

Done.

```

HTTPError: Response code 401 (Unauthorized)
    at onResponse (D:\Twitch API Development\TwitchAppAnalytics\node_modules\got\dist\source\as-promise\index.js:124:28)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: undefined,
  timings: {
    start: 1592765404281,
    socket: 1592765404281,
    lookup: 1592765404294,
    connect: 1592765404305,
    secureConnect: 1592765404326,
    upload: 1592765404326,
    response: 1592765404475,
    end: 1592765404476,
    error: undefined,
    abort: undefined,
    phases: {
      wait: 0,
      dns: 13,
      tcp: 11,
      tls: 21,
      request: 0,
      firstByte: 149,
      download: 1,
      total: 195
    }
  }
} { error: 'Unauthorized', status: 401, message: 'Invalid OAuth token' }

```

Saying Invalid OAuth Token but I am Validating the OAuth Token and its coming back fine.  
Posting my Validating Code below

```

async function requestValidate() {

request.post('https://id.twitch.tv/oauth2/token?client_id='+process.env.TWITCH_CLIENT_ID+'&client_secret='+process.env.TWITCH_SECRET+'&grant_type=client_credentials', function (error, response, body) {

    console.error('error:', error); // Print the error if one occurred

    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received

    console.log('body:', body); // Print the HTML for the Google homepage.

    console.log(body);

    const authJson = JSON.parse(body);

    const accessToken = authJson.access_token;

      got({

          url: "https://id.twitch.tv/oauth2/validate",

          method: "GET",

          headers: {

              Authorization: "OAuth " + accessToken

          },

          responseType: "json",

      }).then(resp => {

        console.log("Validated: ", resp.body);

        if (resp.body.expires_in <= 3600) {

            twitch.makeClientCred();

        } else {

            // it"s ok

        }

    }).then(stream => {

      RequestStreams()

    })

    .catch(err => {

        console.error(err);

        twitch.makeClientCred();

    });

    

});

}

```

Console:

```

https://id.twitch.tv/oauth2/token?client_id=REDACTED&client_secret=REDACTED&grant_type=client_credentials
Twitch auth sample listening on port 3000!
error: null
statusCode: 200
body: {"access_token":"REDACTED","expires_in":4783417,"token_type":"bearer"}

{"access_token":"REDACTED","expires_in":4783417,"token_type":"bearer"}

Validated: {
  client_id: 'REDACTED',
  scopes: [],
  expires_in: 4783417
}

```

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [June 21, 2020, 6:56pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/8 "2020-06-21T18:56:19Z")

</div>

hmm can you put _all_ your code up somewhere.

I have a feeling accessToken is blank in your call to streams.

Additionally you are mixing both requests and got. Which is “ok” just odd to use two libraries that do the same thing

---

<div class="post-metadata">

**Author:** ![AdamJN](https://avatars.discourse-cdn.com/v4/letter/a/c89c15/32.png) [@AdamJN](https://discuss.dev.twitch.com/u/AdamJN)\
**Post date:** [June 21, 2020, 7:01pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/9 "2020-06-21T19:01:08Z")

</div>

Yeah, I found I was having issues with requests and Oauth2. Need to remove it at some point really.

> <https://github.com/AdamJNew/AnalyticsTTVAPI/blob/master/index.js>

Also Im storing my variables in a .env file as  
TWITCH\_CLIENT\_ID=‘REDACTED’  
TWITCH\_SECRET=‘REDACTED’

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [June 21, 2020, 7:02pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/10 "2020-06-21T19:02:24Z")

</div>

> <https://github.com/AdamJNew/AnalyticsTTVAPI/blob/master/index.js#L30>

Theres your problem.

You locked the access token to that function, it’s not available to other functions to use. So it’s undefined.

---

<div class="post-metadata">

**Author:** ![AdamJN](https://avatars.discourse-cdn.com/v4/letter/a/c89c15/32.png) [@AdamJN](https://discuss.dev.twitch.com/u/AdamJN)\
**Post date:** [June 21, 2020, 7:14pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/11 "2020-06-21T19:14:46Z")

</div>

Ah, I thought I had checked that. Thanks for the help.

---

<div class="post-metadata">

**Author:** ![system](https://d2opxh93rbxzdn.cloudfront.net/original/2X/0/05909729875cce3b53e59d5561c4d23bb14948fc.png) [@system](https://discuss.dev.twitch.com/u/system)\
**Post date:** [July 21, 2020, 7:14pm UTC](https://discuss.dev.twitch.com/t/server-to-server-endpoint-request-unauthorised/26625/12 "2020-07-21T19:14:49Z")

</div>

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