Dave Conway Piano





Guild Wars 2:

Tomato Yesterday




Twitch JavaScript API redirect_uri Woes

20 August 2015 17:37 EDT under
Development, Site, Twitch

My requests system is just about done! Probably the biggest hiccup I kept running into with it was the Twitch JavaScript API failing to grant an access token, citing a "redirect_uri_mismatch," despite my redirect URI exactly matching what's stated on my Twitch application's settings page.

Well, it turns out that when you redirect to Twitch login/authorization, you also have to be coming from the exact redirect URI, as well. No hashes. No query strings. Even the slash at the end has to match. I can't find supporting documentation for this anywhere; it's solely observational.

Anyone else struggling with this may find the following "hack" useful. At the very top of the JavaScript for the page, I put the following check in:

if (location.href != TWITCH_REDIRECT_URI && location.href.indexOf('access_token=') == -1) {
    location.href = TWITCH_REDIRECT_URI;

Obviously replace TWITCH_REDIRECT_URI with your own, well, uh, Twitch redirect URI. This forces the page to immediately redirect to your redirect URI unless it contains the string "access_token," which Twitch will put (followed by the OAuth token, of course) at the end of your redirect URI after a successful authorization.

Of course, someone could bypass this by putting "access_token" manually into the URL in a hash or query string, but that would be pretty stupid of them. Since I save a couple pieces of user info to the server (username and whether or not they're a follower), I go ahead and validate the OAuth token anyway.

First, you can do the following to get the OAuth token if you don't want to pull it from location.href:

var token = Twitch.getToken();

And you can validate (and get the username) with a simple GET request to to their API, passing the OAuth token along with it (jQuery used for the GET request):

    'https://api.twitch.tv/kraken/?oauth_token=' + token,
    function(data, status) {
        if (!data || !data['token'] || !data['token']['valid']) {
            // Handle an invalid token...

        var username = data['token']['user_name'];


Don't forget to specify a return type of jsonp when making requests directly to the Twitch REST API. If you're using jQuery, it goes ahead and sets the cross-domain callback for you, so you don't have to mess with any of it. Pretty nice.

Hope this helps someone!