Get viewer username

I would like to get the viewer username to use inside my extension.
This is how I’m doing it right now (it’s client side)

window.Twitch.ext.onAuthorized(async (auth) => {

      try {
        if (window.Twitch.ext.viewer.isLinked) {
          const endpointUrl = "https://api.twitch.tv/helix/users";
          const url = `${endpointUrl}?id=${window.Twitch.ext.viewer.id}`;
          const response = await fetch(url, {
            headers: {
              "client-id": auth.clientId,
              Authorization: `Extension ${auth.helixToken}`,
            },
          });
          const body = await response.json();
          cardUser = body.data.at(0)?.display_name || cardUser;
        }
      } catch (error) {
        console.error('Error fetching user data:', error);
      }

Problem is that it only get my username and not the others. I don’t why it’s because I’m the ower of the channel or the owner of the extension. If I’m the one using it, it works, but for others, it doesn’t.
Any Suggestion?

Your code gets the username of the user using the extension.

Theres no fault there that I can see

So in client side, get the client side viewer ID and using the client side helix token get the viewers name

So this looks correct

Edit: the other user/viewer has logged into the extension? Broadcasters are auto logged in. Viewers have to opt in to sharing their userID with the extension first

Oh ok, so I need to log the user into the extension.
Do I need to do the OAuth process? The extension is a video component, can it be done in there?

No, extensions provide a login mechansim for viewers to share their ID with the extension, without having to do oAuth.

Broadcasters cannot be unauthed hence it worked for testing the extension as the broadcaster.

See: Extensions Reference | Twitch Developers

if the user isn’t logged in then viewer.id isn’t populated

compared to

Ok now I can get the the viewerId but it only works if the viewer allow access in the extension settings.
Is there a way to request access directly in the extension instead that in the settings? So it’s the first thing the viewer does

user requestIDShare that I linked to

users to share IDs either:

  • click the [dude] icon below the box for a panel
  • in the slightly hidden settings for a overlay/video componenet
  • via a JS function call, which I usually find to a button

So

The login/logout button here invokes window.Twitch.ext.actions.requestIdShare() to trigger the share prompt

is there a way to verify if the user has accepted to share their id?
I would like to permit the usage of the extension only if the viewer accept to share the id

window.Twitch.ext.viewer.isLinked

Reference: Extensions Reference | Twitch Developers

1 Like