How to get Refresh Token for Spotify Web API?

Viewed 204

I am working on a project using the Spotify Web JS API. I am able to successfully get the AccessToken, but I am coming across the issue of the token expiring and have found that I need to get a refresh token. Here is how I am currently getting the access token.

 useEffect(() => {
    const hash = window.location.hash;
    let token = window.localStorage.getItem("token");
    if (!token && hash) {
      token = hash
        .substring(1)
        .split("&")
        .find((elem) => elem.startsWith("access_token"))
        .split("=")[1];

      window.location.hash = "";
      window.localStorage.setItem("token", token);

      setToken(token);
    }
      spotify.setAccessToken(token);

      spotify.getMyRecentlyPlayedTracks({ limit: 50 }).then((data) => {
        setRecentlyPlayed(data.items);
      });
      spotify.getMySavedAlbums().then((user) => {
        console.log("Saved albums:", user);
      });
      spotify.getFollowedArtists().then((user) => {
        setNumberArtistsFollowing(user.artists.total);
      });

      spotify.getMyCurrentPlayingTrack().then((data) => {
        if (data) {
          setCurrentlyPlaying(data);
        }
      });

      spotify.getMe().then(setUserProfile);
    
    setToken(token);
  }, []);

I have no experience with refresh tokens as this is my first project with tokens in general. Could anyone give me a hand? I am thinking that I need to request a refresh token in my code if the localstorage contains a token, do this on every page load regardless of whether the token is expired or not. I am unsure of how to get this refresh token though. Thank you!

0 Answers
Related