@@ -29,9 +29,11 @@ import { developmentConfig } from './config/development'
2929import { productionConfig } from './config/production'
3030import {
3131 addAppInfoMiddleware ,
32- addRequestSignatureMiddleware
32+ addRequestSignatureMiddleware ,
33+ addTokenRefreshMiddleware
3334} from './middleware'
3435import { OAuth } from './oauth'
36+ import { OAuthTokenStore } from './oauth/tokenStore'
3537import {
3638 PaymentRouterClient ,
3739 getDefaultPaymentRouterClientConfig
@@ -133,7 +135,7 @@ export const createSdkWithServices = (config: SdkConfig) => {
133135 )
134136 }
135137
136- // Initialize APIs
138+ // Initialize APIs (also creates tokenStore and oauth)
137139 const apis = initializeApis ( {
138140 config,
139141 apiKey,
@@ -142,17 +144,7 @@ export const createSdkWithServices = (config: SdkConfig) => {
142144 services
143145 } )
144146
145- // Initialize OAuth
146- const oauth = isBrowser
147- ? new OAuth ( {
148- appName,
149- apiKey,
150- logger : services . logger
151- } )
152- : undefined
153-
154147 return {
155- oauth,
156148 ...apis
157149 }
158150}
@@ -459,11 +451,36 @@ const initializeApis = ({
459451 } )
460452 ]
461453
454+ // Token store for PKCE flow — provides dynamic accessToken to Configuration
455+ const tokenStore = new OAuthTokenStore ( )
456+
457+ // Auto-refresh middleware — intercepts 401s and retries with a fresh token.
458+ const oauth =
459+ typeof window !== 'undefined'
460+ ? new OAuth ( {
461+ apiKey,
462+ tokenStore,
463+ basePath
464+ } )
465+ : undefined
466+
467+ if ( apiKey && oauth ) {
468+ middleware . push (
469+ addTokenRefreshMiddleware ( {
470+ oauth
471+ } )
472+ )
473+ }
474+
475+ const bearerToken = 'bearerToken' in config ? config . bearerToken : undefined
476+
462477 const apiClientConfig = new Configuration ( {
463478 fetchApi : fetch ,
464479 middleware,
465480 basePath,
466- accessToken : 'bearerToken' in config ? config . bearerToken : undefined
481+ // Static bearerToken takes precedence; otherwise use the dynamic store
482+ // so PKCE login can inject tokens after construction.
483+ accessToken : bearerToken ?? tokenStore . asAccessTokenProvider ( )
467484 } )
468485
469486 const tracks = new TracksApi ( apiClientConfig , services )
@@ -506,6 +523,8 @@ const initializeApis = ({
506523 const search = new SearchApi ( apiClientConfig )
507524
508525 return {
526+ oauth,
527+ tokenStore,
509528 tracks,
510529 users,
511530 albums,
0 commit comments