Getting rate limit response headers in javascript

Hi All

I’m sure that I am missing understanding a fundamental concept here but I am unable to access the Response headers to manage rate limiting using the new API from javascript. Here’s my code:

var twitchHelixHeaders = {
    'Content-Type': 'application/json',
    'Client-Id': 'bloominhellwhydoesntthiswork'
}

function getStream() {
   
	$.ajax({
	    url: "https://api.twitch.tv/helix/users?login=" + channel,
        headers: twitchHelixHeaders,
        success: getStreamCallback
	})
    
}

function getStreamCallback (data, status, response) {
    
    //We are going to need to manage API call Rate Limits as the Helix API wil enforce Rate Limiting
    console.log(response.getResponseHeader('Ratelimit-Remaining'));
    console.log(response.getResponseHeader('Pragma'));
    console.log(response.getAllResponseHeaders());
}

What I see in the console is:

null

no-cache

pragma: no-cache
content-type: application/json; charset=utf-8
cache-control: no-cache, no-store, must-revalidate, private
expires: 0

Basically it looks like the headers are not available to me in javascript using getAllResponseHeaders() however in the Chrome debugger I see the Response with all the required headers included.

This seems like a pretty common problem with javascript, possibly related to CORS but even if I try to enable CORS there is not any change. I’ve also noticed that if the API response includes an access-control-allow-headers list the ratelimit headers are not included but that actually doesn’t make any difference to the results I see in javascript I can only ever access the common headers and nothing custom.

Any thoughts?

Thanks
Adrian

Just wrote this fetch version and it definitely works. Try with lowercase header keys.

const clientID = '';

function getUser(username) {
    let url = `https://api.twitch.tv/helix/users?login=${username}`;
    let headers = new Headers({
            'Client-ID': clientID
        });
    return fetch(url, { headers })
    .then(res => {
        let { headers } = res;
        let rateLimit = {
                limit: parseInt(headers.get('ratelimit-limit')),
                remaining: parseInt(headers.get('ratelimit-remaining')),
                reset: parseInt(headers.get('ratelimit-reset'))
            };
        return res.json()
        .then(data => {
            data.rateLimit = rateLimit;
            return data;
        });
    });
}
let username = 'alca';
getUser(username)
.then(({ rateLimit: { limit, remaining, reset }, data: [ { display_name, id } ] }) => {
    console.log(`Got user data ${display_name} (${id})`);
    let seconds = reset - Date.now() / 1000;
    console.log(`${remaining}/${limit} calls remain for ${~~seconds} seconds.`);
});

Got user data Alca (7676884)
18/30 calls remain for 50 seconds.

Hi Alca

Thanks for the suggestions but I get the same issue:

Got user data unshapedAdrian (45471252)
NaN/NaN calls remain for 0 seconds.

Basically from debugging it looks like the headers on the response are not available and so when I try to parse them out using your code I just get NaN.

I’m running this inside Chrome, I guess (as it worked for you) that you are running outside a browser is that correct.

Thanks again
Adrian

Sounds like Twitch needs to add the rate limit headers to the Access-Control-Expose-Headers header.

1 Like

That would seem to be the case.

If I test this on a server that I own and add the relevant Access-Control-Expose-Headers header it is then accessible inside the javascript code.

Do I just cross my fingers and hope that this gets implemented going forward?

Thanks for your help everyone, as always awesome community.

Adrian

Hey, Helix Dev here. Just letting you know I’m going to look into this :slight_smile:

Also for Helix you don’t need to add the Content-Type header.

Thanks!

2 Likes

Thanks very much for taking a look if you need any more information then please let me know.

Also thanks for the tip on Content-Type :slight_smile:

Adrian

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