Jamming: 401 Invalid Access Token on Search

When attempting to use search on the Jamming project, I am getting a 401 error code with the message “Invalid Access Token.” Logging the header to the console looks like all the info is correct but for some reason it isn’t going through correctly. Any help would be greatly appreciated! Code below:

const clientID = 'My_Id_Was_Here';
const redirectUri = 'http://localhost:3000';
let accessToken;

const Spotify = {
    getAccessToken(){
        if(accessToken){
            return accessToken;
        }

        //check for token match
        const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
        const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

        if(accessTokenMatch && expiresInMatch){
            accessToken = accessTokenMatch;
            const expiresIn = Number(expiresInMatch[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;
        }
    },

    search(term) {
        const accessToken = Spotify.getAccessToken();
        const headers = {Authorization: `Bearer ${accessToken}`};

        return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {headers: headers}
        ).then(response => {
          return response.json()
        }).then(jsonResponse => {
          if (!jsonResponse.tracks) {
            return [];
          } 
          return jsonResponse.tracks.items.map(track => {
            return {
              id: track.id,
              name: track.name,
              artist: track.artists[0].name,
              album: track.album.name,
              uri: track.uri,
            }
          });
        });
      },

    savePlaylist(name, trackUris){
        if(!name || !trackUris){
            return;
        }

        const accessToken = Spotify.getAccessToken();
        const headers = { Authorization: `Bearer ${accessToken}`};
        let userId;

        return fetch('https://api.spotify.com/v1/me', {headers: headers}
        ).then(response => response.json()
        ).then(jsonResponse => {
            userId = jsonResponse.id;
            return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`,
                {
                    headers: headers,
                    method: 'POST',
                    body: JSON.stringify({ name: name })
                }).then(response => response.json()
                ).then(jsonResponse => {
                    const playlistId = jsonResponse.id;
                    return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, {
                        headers: headers,
                        method: 'POST',
                        body: JSON.stringify({uris: trackUris})
                    })
                });
        });
        

    }
}

export default Spotify;

Thanks in advance!

Hi Mike,

if you just log the accessToken, you’ll probably see that it is an array. The access token you need is in the second item: accessToken[1].