Jamming React - getAccessToken() method

Please support. I am kind of unexperienced in DOM and lwith a lot of effort I have almost reached the end of the jamming project but I am seriously having troubles on fully understand how part of the code from the getAccessToken() method works.

I understand that when I am running the app in the browser the “search” button will trigger the Spotify.search() method in Spotify.js which in turn will use the Spotify.getAccessToken() method to get the accessToken.

What I really find hard to understand why we are looking for the accessToken value into the current window.location.href (using .match) if we are supposed to be “parked” at the URL “http://localhost:3000/” ??

I hope I explained myself and you can give me some reference that can help me review some basic concepts…


            return accessToken;
        **const accessToken_Match = window.location.href.match(/access_token=([^&]*)/);**
**        const expiresIn_Match =  window.location.href.match(/expires_in=([^&]*)/);**
        if (accessToken_Match && expiresIn_Match){
            accessToken = accessToken_Match[1]; 
            const expiresIn = Number(expiresIn_Match[1]); 
            window.setTimeout(() => accessToken = '', expiresIn * 1000);
            window.history.pushState('Access Token', null, '/');
            return accessToken;
        } else {
            const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`
            window.location = accessUrl;

I think I can answer to this for you.
First of all, how does the Implicit Authorization Auth of Spotify work?
You “build” a link with all the parameters, aka const accessUrl
This is a link that will lead you to the Spotify Authorization page: once you (the user) agree to give access to your data, your browser will be redirected to
Which in this case is the localhost page, BUT there is a difference now! Normally your browser URL will look like this:


But after giving Spotify access and get redirected, it will look something like this:


This is when the match() function comes in play: window.location.href returns the URL you have in your browser at that instance, whereas match() will use a regular expression to capture the access token from this URL.

Hope I helped!

So, this is why search doesn’t work the first time you click the button, you receive the acces token after it.
Any fix for this?