How to retrieve username from Twitch API without button clicks

I’m working with the Twitch API and jQuery but I’m stuck on something. I need to fetch the current user’s display name automatically when the page loads, but I don’t want to use any buttons or input fields to show it.

Here’s a sample of what I’m trying to modify:

$(document).ready(function() {
  Twitch.api({method: 'user'}, function(err, userInfo) {
    var displayName = userInfo.display_name;
    // I want to use displayName here without showing it in inputs
  });
});

Is there a way to automatically retrieve and store the username in a variable that I can use elsewhere in my code? I basically want the API call to happen behind the scenes without any user interaction required.

You’re on the right track. The main issue is probably authentication - the Twitch API won’t work without it. Make sure you’ve set up your Twitch client with the client ID and got the user authenticated before calling the API. Once you get the displayName from the callback, just store it globally or pass it around. Something like window.currentUser = displayName; works for global access. Just remember this API call is async, so any code that needs the username has to be inside the callback or called from there. The auth state sticks around between page loads if the user already authorized your app.

Had this exact issue when I built my Twitch integration last year. Your code structure looks right, but there are some gotchas. First - make sure authentication’s done before hitting the API. I wrap my Twitch.api calls in a function that checks auth status first. Second - timing matters since the API call’s async. Use promises or callbacks for anything that depends on that data. For storing usernames, I just create a simple object instead of cluttering global scope. One heads up - the old Twitch JavaScript SDK’s deprecated. If you’re starting fresh, consider their newer auth flow with direct HTTP requests instead.

yeah, this’ll work once you get auth figured out. i usually create a simple function like function getUser() { return window.twitchUser || null; } and call it whenever i need the username. just make sure you handle errors in your callback - the api might fail or the user might not be logged in properly.