<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Natasha Barsova on Medium]]></title>
        <description><![CDATA[Stories by Natasha Barsova on Medium]]></description>
        <link>https://medium.com/@natashabarsova?source=rss-df72770490f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sAhyvJARkbxhFdfjBndbMw.jpeg</url>
            <title>Stories by Natasha Barsova on Medium</title>
            <link>https://medium.com/@natashabarsova?source=rss-df72770490f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:44:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@natashabarsova/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple spotify player in react]]></title>
            <link>https://medium.com/@natashabarsova/simple-spotify-player-in-react-b140df4a2f09?source=rss-df72770490f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b140df4a2f09</guid>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Natasha Barsova]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 18:32:25 GMT</pubDate>
            <atom:updated>2019-07-10T18:40:08.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMXncWhddVrZyx_a9EW_Fg.png" /></figure><p>In this article I will describe an implementation of a simple player for spotify tracks as react component, that receives spotify track identificator as a property, opens an authorization dialog in the new window and starts the playback of the track after successfull authorization.</p><p>To be able to play spotify tracks from a react application, we need to make use both of spotify <a href="https://developer.spotify.com/documentation/web-playback-sdk/">web playback SDK</a> and <a href="https://developer.spotify.com/documentation/web-api/">spotify API</a>. Spotify web playback SDK is a set of scripts that create an instance of spotify player (unlike for example youtube api, there is no element of the dom corresponding to the player, just a javascript object). Having obtained the player object with an unique id, you can ask the user to authorize and send fetch requests to the spotify api endpoints to start, pause and seek in the spotify tracks. Right now spotify api calls will only work for spotify premium users, for others the authorization will be successful, but all subsequent fetches will return 400 errors.</p><p><strong>Spotify Dashboard Configuration</strong></p><p>You need to register your application and specify valid redirect urls (the urls to which spotify authorization endpoint will redirect you after completing authorizatuon) via <a href="https://developer.spotify.com/dashboard/applications">developer dashboard</a>. The setup is pretty straightforward, you add a new application, choose its type and then configure redirect urls in the settings. Don’t forget to include localhost with the right port for debugging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHNjJZrP4PxvYJODQ2f50Q.png" /><figcaption>Spotify developer dashboard</figcaption></figure><p>Then you can copy client id from the dashboard and use it in authorization process in your application.</p><p><strong>Playback SDK integration</strong></p><p>So, now let’s get to coding and see how all of this can be wrapped inside a react component. I used a simple react app with typescript support for this example.</p><p>In a non-react web application, according to the <a href="https://developer.spotify.com/documentation/web-playback-sdk/quick-start/">spotify web SDK documentation</a> we are just supposed to use the &lt;script&gt; tag on our page.</p><pre>&lt;script src=&quot;https://sdk.scdn.co/spotify-player.js&quot;&gt;&lt;/script&gt;</pre><p>In order to load external script and use its objects in the react component, we can use script cache as described in <a href="https://www.fullstackreact.com/articles/Declaratively_loading_JS_libraries/index.html">this approach</a>.</p><p>First of all, we create a SpotifyPlayerContainer component, which will contain all the player functionality. In the constructor we load the sdk scripts.</p><pre><strong>class </strong>SpotifyPlayerContainer <strong>extends </strong>Component {</pre><pre><strong>public constructor</strong>(props: ISpotifyPlayerProps) {<br>    <strong>super</strong>(props);<br><br>    <strong>new </strong>ScriptCache([<br>        {<br>            <strong>name</strong>: <strong>&quot;https://sdk.scdn.co/spotify-player.js&quot;</strong>,<br>            <strong>callback</strong>: <strong>this</strong>.<em>spotifySDKCallback<br>        </em>}]);<br><br>   }])<br>// ...<br>}</pre><p>And then implement the callback, in which we again attach a required callback to the window object. In it we will create the player object, attach error and status listeners to it as described in <a href="https://developer.spotify.com/documentation/web-playback-sdk/quick-start/">SDK Quick Start</a> and then save the player instance in a component state.</p><pre><strong>private </strong><em>spotifySDKCallback </em>= () =&gt; {<br>    <strong><em>window</em></strong>.onSpotifyWebPlaybackSDKReady = () =&gt; {<br>       const token = &#39;[My Spotify Web API access token]&#39;;<br>       const player = new Spotify.Player({<br>       name: &#39;Spotify Demo Player&#39;,<br>       getOAuthToken: cb =&gt; { cb(token); }<br>      });</pre><pre>    spotifyPlayer.<strong>addListener</strong>(<strong>&#39;player_state_changed&#39;</strong>, ...<br>       // add event listeners to the player</pre><pre>    <strong>this</strong>.setState({spotifyPlayer});<br>}</pre><p>What is missing here is this web api access token for the getOAuthToken function, to get which, we must implement <a href="https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow">spotify api authorization</a> using authorization code flow.</p><p><strong>Spotify API authorization implementation</strong></p><p>Spotify authorization in itself requires only client id that we obtained in the dashboard for our application. Subsequent calls to api to start or pause playback will need device id from the player, so we will have to synchronize that with sdk scripts loading.</p><p>Technically, to authorize, you need to point your browser to an spotify authorization URL, providing in the request parameters your app client id (obtained in developer dashboard) and a redirect url, that is where spotify will redirect your browser with spotify access token as a hash parameter. We will do that in the simple component, that opens a new window using react portal.</p><pre><strong>class </strong>SpotifyAuthWindow <strong>extends </strong>Component {<br><br>    <strong>private externalWindow</strong>: Window | <strong>null</strong>;<br>    <strong>private containerEl</strong>: HTMLDivElement;<br>    <strong>private SCOPE_LIST </strong>= <strong>&quot;streaming&quot;</strong>;<br>    <br>    <strong>constructor</strong>(props: <strong>any</strong>) {<br>        <strong>super</strong>(props);<br>        <strong>this</strong>.<strong>containerEl </strong>= <strong><em>document</em></strong>.createElement(<strong>&#39;div&#39;</strong>);<br>        <strong>this</strong>.<strong>externalWindow </strong>= <strong>null</strong>;<br>    }<br><br>    <strong>public </strong>componentDidMount(): <strong>void </strong>{<br><br>        <strong>this</strong>.<strong>externalWindow </strong>=          <br>            <strong><em>window</em></strong>.open(<strong>&quot;https://accounts.spotify.com/authorize?&quot; </strong>+<br>                        <strong>&quot;client_id=&quot; </strong>+ // your client id<br>                        <strong>&quot;&amp;response_type=token&quot; </strong>+<br>                        <strong>&quot;&amp;redirect_uri=&quot; + <em>window</em></strong>.<strong>location</strong>.<strong>origin +       <br>                        &quot;&amp;show_dialog=true&quot; </strong>+<br>                        <strong>&quot;&amp;scope=&quot;</strong>+<strong>this</strong>.<strong>SCOPE_LIST</strong>, <strong>&#39;&#39;</strong>, <br>                        <strong>&quot;width=600, height=500&quot;</strong>);<br>    }<br><br><br>    <strong>public </strong>render() {<br>        <strong>return </strong>ReactDOM.<em>createPortal</em>(<strong>this</strong>.<strong>props</strong>.<strong>children</strong>,<br>                                     <strong>this</strong>.<strong>containerEl</strong>);<br>    }<br>}</pre><p>As you can see, the redirect url is our just the root url of our app. That means, that after spotify endpoint performs authorization, our app will be loaded in new window we opened with portal. Then we can add checks for hash parameters on initial application load, extract spotify access token and put it in the local storage and then just close the window. The original component, that initiated authorization, will subscribe to storage events, and upon receiving the token will start using it.</p><p>So we replace original in our application index</p><pre>ReactDOM.render(&lt;<strong>App </strong>/&gt;, <strong><em>document</em></strong>.getElementById(<strong>&#39;root&#39;</strong>));</pre><p>with this:</p><pre><strong>const </strong>hashStr = <strong><em>window</em></strong>.<strong>location</strong>.<strong>hash</strong>; <br><em>// everything in address after #, here spotify puts successfull auth tokens<br></em><strong>const </strong>searchStr = <strong><em>window</em></strong>.<strong>location</strong>.<strong>search</strong>; <br><em>// everything in address after ?, here spotify puts access denials<br></em><strong>const </strong>hashParams = <em>decodeHashParams</em>(hashStr.slice(1,  <br>                                    hashStr.<strong>length</strong>));<br><strong>const </strong>searchParams = <em>decodeHashParams</em>(searchStr.slice(1, <br>                                      searchStr.<strong>length</strong>));<br><br><strong>if </strong>(hashParams.access_token) {<br>    <strong><em>localStorage</em></strong>.setItem(SPOTIFY_ACCESS, <br>                         SpotifyAccess.<em>ALLOWED</em>);     <br>    <strong><em>localStorage</em></strong>.setItem(SPOTIFY_AUTH_TOKEN,    <br>                         hashParams.access_token);<br>    <strong><em>window</em></strong>.close();<br>} <strong>else if </strong>(searchParams.error) {<br>    <strong><em>localStorage</em></strong>.setItem(SPOTIFY_ACCESS, <br>                         SpotifyAccess.<em>DENIED</em>);<br>    <strong><em>window</em></strong>.close();<br>} <strong>else </strong>{<br>    ReactDOM.render(&lt;<strong>App </strong>/&gt;, <strong><em>document</em></strong>.getElementById(<strong>&#39;root&#39;</strong>));<br>}</pre><p><strong>Bringing it all together</strong></p><p>Now we must subscribe our player component to local storage events changing in component constructor:</p><pre><strong>public constructor</strong>(props: ISpotifyPlayerProps) {<br>    <strong>super</strong>(props);<br><br>    <strong><em>window</em></strong>.addEventListener(<strong>&quot;storage&quot;</strong>,   <br>                             <strong>this</strong>.<em>authorizeSpotifyFromStorage</em>);</pre><p>And update spotify credentials in state as soon, as they appear in the storage</p><pre><strong>private </strong><em>authorizeSpotifyFromStorage </em>= (e: StorageEvent) =&gt; {<br><br>    <strong>if </strong>(e.<strong>key </strong>=== SPOTIFY_AUTH_TOKEN) {<br>        <strong>const </strong>spotifyAccessToken = e.<strong>newValue</strong>;<br><br>        <strong>const </strong>spotifyAccess = <em>getSpotifyAccessFromStorage</em>();<br><br>        <strong>if </strong>(spotifyAccess === SpotifyAccess.<em>DENIED</em>) {<br>            <strong>this</strong>.setState({<br>                <strong>spotifyAccess</strong>: SpotifyAccess.<em>DENIED</em>   <strong><br>            </strong>});<br>        } <strong>else if </strong>(spotifyAccessToken !== <strong>null</strong>) {<br>            <strong>this</strong>.setState({<br>                <strong>spotifyAccessToken</strong>: spotifyAccessToken,<br>                <strong>spotifyAccess</strong>: SpotifyAccess.<em>ALLOWED</em><strong><br>            </strong>});<br>        }<br>        <strong>this</strong>.<em>connectToPlayer</em>();<br>    }<br>}</pre><p>Now in our SDK loaded callback we can use the spotifyAccessToken from the state:</p><pre><strong><em>window</em></strong>.onSpotifyWebPlaybackSDKReady = () =&gt; {<br><br>        <strong>if </strong>(<strong>this</strong>.<strong>state</strong>.<strong>spotifyAccess </strong>!== SpotifyAccess.<em>DENIED</em>) {<br>            <strong>const </strong>spotifyPlayer = <strong>new </strong>Spotify.<em>Player</em>({<br>                <strong>name</strong>: <strong>&#39;React Spotify Player&#39;</strong>,<br>                getOAuthToken: cb =&gt; {<br>                    cb(<strong>this</strong>.<strong>state</strong>.<strong>spotifyAccessToken</strong>);<br>                }<br>            });<br>// ...<br>}</pre><p>As soon as spotify endpoint has sent us the token, we are ready to connect to player. We use timeout to synchronize authorization with script loading, as soon as the scripts are loaded and the player is there, we perform the actual connect and retrieve its device id.</p><pre><strong>private </strong><em>connectToPlayer </em>= () =&gt; {<br>    <strong>if </strong>(<strong>this</strong>.<strong>state</strong>.<strong>spotifyPlayer</strong>) {<br>        <em>clearTimeout</em>(<strong>this</strong>.<strong>connectToPlayerTimeout</strong>);</pre><pre>      // add event listeners to player getting into &quot;ready&quot; state<br>       <strong>this</strong>.<strong>state</strong>.<strong>spotifyPlayer</strong>.<strong>addListener</strong>(<strong>&#39;ready&#39;</strong>, <br>        ({device_id}) =&gt; {<br>            <strong>this</strong>.setState({<br>                <strong>spotifyDeviceId</strong>: device_id,<br>                <strong>spotifyPlayerReady</strong>: <strong>true<br>            </strong>});<br>        });</pre><pre>        <strong>this</strong>.<strong>state</strong>.<strong>spotifyPlayer</strong>.connect();<br>    } <strong>else </strong>{<br>        <strong>this</strong>.<strong>connectToPlayerTimeout </strong>= <br>                <em>setTimeout</em>(<strong>this</strong>.<em>connectToPlayer</em>.bind(<strong>this</strong>), 1000);<br>    }<br>}</pre><p><strong>Starting, pausing and resuming playback</strong></p><p>So, now we have a player object, that is ready to play spotify tracks for us. We add user controls, that will start/pause playback to our player component. Two icons from <a href="https://react-icons.netlify.com/">react-icons</a> package are used as buttons for playback start/pausing.</p><pre>render() {<br>  <strong>return </strong>(<br>     // ... <br>     &lt;<strong>div className=</strong>{styles.player}&gt;<br>     {<strong>this</strong>.<strong>state</strong>.<strong>spotifyPlayerReady </strong>&amp;&amp;<br>        &lt;<strong>div onClick=</strong>{() =&gt; {<br>            <strong>if </strong>(!<strong>this</strong>.<strong>state</strong>.<strong>playbackOn</strong>) {<br>                  <strong>this</strong>.<em>startPlayback</em>(<strong>this</strong>.<strong>props</strong>.<strong>playingRecordingId</strong>);<br>               } <strong>else </strong>{<br>                  <strong>if </strong>(<strong>this</strong>.<strong>state</strong>.<strong>playbackPaused</strong>) {<br>                      <strong>this</strong>.<em>resumePlayback</em>();<br>                  }<br>               }}}&gt;&lt;<strong>FaPlay</strong>/&gt;&lt;/<strong>div</strong>&gt;}<br>     {<strong>this</strong>.<strong>state</strong>.<strong>spotifyPlayerReady </strong>&amp;&amp; <strong>this</strong>.<strong>state</strong>.<strong>playbackOn </strong>&amp;&amp;<br>        &lt;<strong>div onClick=</strong>{() =&gt; {<br>            <strong>if </strong>(!<strong>this</strong>.<strong>state</strong>.<strong>playbackPaused</strong>) {<br>              <strong>this</strong>.<em>pauseTrack</em>();<br>            }}}&gt;&lt;<strong>FaPause</strong>/&gt;<br>        &lt;/<strong>div</strong>&gt;}<br>      &lt;/<strong>div</strong>&gt;);<br>    }</pre><p>The startPlayback, pausePlayback and resumePlayback methods are basically fetch calls to the corresponding api endpoints.</p><pre><strong>private </strong><em>startPlayback </em>= (spotify_uri: <strong>string</strong>) =&gt; {<br>  <em>fetch</em>(<strong>&quot;https://api.spotify.com/v1/me/player/play?&quot; </strong>+<br>    <strong>&quot;device_id=&quot; </strong>+ <strong>this</strong>.<strong>state</strong>.<strong>spotifyDeviceId</strong>, {<br>    <strong>method</strong>: <strong>&#39;PUT&#39;</strong>,<br>    <strong>body</strong>: <strong><em>JSON</em></strong>.stringify({<strong>uris</strong>: [spotify_uri]}),<br>    <strong>headers</strong>: {<br>     <strong>&#39;Content-Type&#39;</strong>: <strong>&#39;application/json&#39;</strong>,<br>     <strong>&#39;Authorization&#39;</strong>: <strong>`Bearer </strong>${<strong>this</strong>.<strong>state</strong>.<strong>spotifyAccessToken</strong>}<strong>`<br>    </strong>}}).then((ev) =&gt; {<br>        <strong>if </strong>(ev.<strong>status </strong>=== 403) {<br>            <strong>this</strong>.setState({<br>                <strong>spotifyAccess</strong>: SpotifyAccess.<em>NO_PREMIUM<br>            </em>}); <br>        // notify the user, possibly re-request authorization<br>        } <strong>else </strong>{<br>            <strong>this</strong>.setState({<br>                <strong>playbackOn</strong>: <strong>true</strong>, <br>                <strong>playbackPaused</strong>: <strong>false<br>            </strong>});<br>        }<br>    }).catch((error) =&gt; {<br>        <strong>// ...</strong><br>    })<br>};</pre><p>The endpoints will return 403 codes if the user does not have premium rights for playback. In that case you would want to show a notification and may be re-request authorization using the SpotifyAuthWindow component again.</p><p>Pausing playback is done via following api call:</p><pre><em>fetch</em>(<strong>&quot;https://api.spotify.com/v1/me/player/pause?&quot; </strong>+<br>    <strong>&quot;device_id=&quot; </strong>+ <strong>this</strong>.<strong>state</strong>.<strong>spotifyDeviceId</strong>, {<br>    <strong>method</strong>: <strong>&#39;PUT&#39;</strong>,<br>    <strong>headers</strong>: {<br>        <strong>&#39;Content-Type&#39;</strong>: <strong>&#39;application/json&#39;</strong>,<br>        <strong>&#39;Authorization&#39;</strong>: <strong>`Bearer </strong>${<strong>this</strong>.<strong>state</strong>.<strong>spotifyAccessToken</strong>}<strong>`<br>    </strong>}})<br>      .then((ev) =&gt; {<br>          <strong>this</strong>.setState({<strong>playbackPaused</strong>: <strong>true</strong>})})<br>      .catch(error) =&gt; {<br>        <strong>// ...<br>   })<br>}</strong></pre><p>And resuming paused playback is just a call to the same player api, but without specified URI in the body.</p><pre><em>fetch</em>(<strong>&quot;https://api.spotify.com/v1/me/player/play?&quot; </strong>+<br>    <strong>&quot;device_id=&quot; </strong>+ <strong>this</strong>.<strong>state</strong>.<strong>spotifyDeviceId</strong>, {<br>    <strong>method</strong>: <strong>&#39;PUT&#39;</strong>,<br>    <strong>headers</strong>: {<br>        <strong>&#39;Content-Type&#39;</strong>: <strong>&#39;application/json&#39;</strong>,<br>        <strong>&#39;Authorization&#39;</strong>: <strong>`Bearer </strong>${<strong>this</strong>.<strong>state</strong>.<strong>spotifyAccessToken</strong>}<strong>`<br>    </strong>},})<br>      .then((ev) =&gt; {<br>         <strong>this</strong>.setState({<strong>playbackPaused</strong>: <strong>false</strong>})})<br>      .catch(error) =&gt; {<br>        <strong>// ...<br>  })<br>}</strong></pre><p>So now our demo player is complete. In a more realistic application you will need to add authorization token renewal mechanism (spotify tokens expire in one hour), as well as more player-related functionality like switching tracks, displaying track metadata and seeking, which are all possible using s<a href="https://developer.spotify.com/documentation/web-api/reference/">potify api endpoints</a>.</p><p>Full working code of the demo spotify player can be downloaded<a href="https://github.com/nbarsova/spotify-react-demo"> here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b140df4a2f09" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>