Search code examples
react-nativeexpotwitch

Twitch API 401 error with React Native Expo


I'm trying to get user info from Twitch with React Native Expo, but it always returns 401 error.

I found that it correctly gets the OAuth token, but the problem occurs after it.

Here's my code:

WebBrowser.maybeCompleteAuthSession();

// Endpoint
const discovery = {
    authorizationEndpoint: 'https://id.twitch.tv/oauth2/authorize',
    tokenEndpoint: 'https://id.twitch.tv/oauth2/token',
    revocationEndpoint: 'https://id.twitch.tv/oauth2/revoke',
};

// Login Screen
export function loginScreen({ navigation }) {
    const [request, response, promptAsync] = useAuthRequest(
        {
            responseType: ResponseType.Token,
            clientId: '(deleted)',
            // For usage in managed apps using the proxy
            redirectUri: makeRedirectUri({ useProxy: true }),
            scopes: ['openid', 'user_read', 'user_subscriptions'],
        },
        discovery
    );

    React.useEffect(() => {
        if (response?.type === 'success') {
            fetch('https://api.twitch.tv/kraken/user', {
                method: 'GET',
                headers: {
                    'Accept': 'application/vnd.twitchtv.v5+json',
                    'Client-ID': '(deleted)',
                    'Authorization': 'OAuth ' + response.params
                }
            })
                .then((data) => {
                    AsyncStorage.setItem('userData', JSON.stringify(data))
                        .then(() => console.log(JSON.stringify(data)))    // console.log for testing
                        .then(() => navigation.navigate('Home'))
                })
                .catch((err) => alert(err))
        }
    }, [response]);

and I referred to this document for the authentication.


Solution

  • Twitch SignIn & get user information using Expo's expo-auth-session.

    Step 1: Create an account and enable two-factor authentication on Twitch developer site.You will get a key.

    Step 2: Install Expo's expo install expo-auth-session

    Step 3: Add Scheme in App.json file

    {
      "expo": {
          "scheme": "myapp"
      }
    }
    

    In order to be able to deep link back into your app, you will need to set a scheme in your project app.config.js, or app.json, and then build your standalone app (it can't be updated with an OTA update). If you do not include a scheme, the authentication flow will complete but it will be unable to pass the information back into your application and the user will have to manually exit the authentication modal (resulting in a cancelled event).

    Step 4:

    import * as AuthSession from 'expo-auth-session';
    // To fetch twitch user information 
    const getTwitchUserInformation = twitchToken => {
        const url = 'https://api.twitch.tv/helix/users';
        const header = {
          Authorization: `Bearer ${twitchToken}`,
          'Client-ID': SOCIAL_CONSTANTS.TWITCH_CLIENT_ID,
        };
    fetch(url, {
          method: 'GET',
          headers: header,
        })
          .then(response => response.json())
          .then(response => {
            const userResponse = response && response.data[0];
            console.log(userResponse);
          })
          .catch(error => {
            console.log(error);
          });
      };
    const signInWithTwitch = async () => {
      const redirectUrl = AuthSession.getRedirectUrl();
      const authUrl = `https://id.twitch.tv/oauth2/authorize?client_id=${ENTER_CLIENT_ID_HERE}&redirect_uri=${redirectUrl}&response_type=token&scope=user:edit+user:read:email&force_verify=true`
      const {type, params} = await AuthSession.startAsync({authUrl});
      if (type === 'success') {
         const {access_token, token_type} = params;           
        getTwitchUserInformation(access_token);
      }
    };
    

    Link - https://medium.com/@rakesh.medpalli/twitch-signin-get-user-information-in-expo-using-expo-auth-session-a6a74812c096