spotify / spotify-web-api-ts-sdk

A Typescript SDK for the Spotify Web API with types for returned data.
Other
372 stars 74 forks source link

How to get access token after return from sdk.authenticate? #129

Open kimfucious opened 3 weeks ago

kimfucious commented 3 weeks ago

This is probably a dumb question, but I gotta ask:

Scenario

  1. React (Next JS/app router) app using Zustand for state management.
  2. Setup sdk in state with SpotifyApi.withUserAuthorization(...
  3. Set that client in state (now available in useStore (i.e. spotify api is a Zustand slice)
  4. Run spotify.authenticate() which ultimately redirects to the callback URL.

In the callback landing page, I can get the code from search params, which is usually used to get the _accesstoken, when using Spotify Web API directly.

Since I'm trying to use @spotify/web-api-ts-sdk, it would seem that sdk.getUserToken();

The problem is that since spotify.authenticate() leaves the app and returns via the callback, state is lost and the sdk is not authenticated, which means that sdk.getUserToken(); returns null.

What I'm thinking is that I can use the Spotify Web API directly (not @spotify/web-api-ts-sdk) to do the initial auth and retrieve the access token, and then initialize the @spotify/web-api-ts-sdk client using const sdk = SpotifyApi.withAccessToken(...) and use the client @spotify/web-api-ts-sdk going foward.

The thing is that this seems overly complicated to the point where it just smells wrong.

Any advice would be most appreciated.

skysteve commented 2 days ago

+1 here - Refreshing tokens seems at best half-baked. I've had to implement my own logic which works 90% of the time but the auto-refresh sometimes screws me over.

A flag autoRefreshToken: false in the constructor would be a quick win personally