The following guide will guide you step by step to create a simple client-side page to host a new Spotify player based on the Web Playback SDK to stream content along with the rest of devices from your home.

Authenticating with Spotify

The Web Playback SDK needs an access token from your personal Spotify Premium account, so the first thing we need to do is to create an application. The application contains your credentials needed to request an access token.

Go to Dashboard, click on the Log in button and accept the grant permissions dialog box. The dashboard is the place where we can create applications and control the API credentials.

Click on the Create an APP button. Go ahead and provide a name and a short description to your new application. Finally accept the terms and conditions and click on Create. Your new application contains your Client Id and Client Secret needed to authorize the application we are about to code!

Since this quick start guide does not cover the authorization flow, we provide a handy button to generate a new access token:

Remember this access token expires in 1 hour. But no worries! Feel free to come back here and generate a new one!

Installation

We are going to start creating a simple HTML template to host the SDK:

<!DOCTYPE html>
<html>
  <head>
    <title>Spotify Web Playback SDK Quick Start</title>
  </head>
  <body>
    <h1>Spotify Web Playback SDK Quick Start</h1>
  </body>
</html>

To install the Web Playback SDK, we need to embed the SDK. Right after the h1 tag, insert the following code:

<script src="https://sdk.scdn.co/spotify-player.js"></script>

Initialization

Once the Web Playback SDK has been correctly included, we can initialize the player immediately. Let’s add a new script tag with the following content (don’t forget to replace the token variable’s value with your previously generated access token):

window.onSpotifyWebPlaybackSDKReady = () => {
  const token = '[My access token]';
  const player = new Spotify.Player({
    name: 'Web Playback SDK Quick Start Player',
    getOAuthToken: cb => { cb(token); },
    volume: 0.5
  });

The onSpotifyWebPlaybackSDKReady method will be executed once the Web Playback SDK has successfully loaded, creating the instance of the Player and receiving the following parameters:

  • name of the Spotify instance.
  • The callback getOAuthToken expected to provide a valid access_token.
  • The volume of the player represented as a decimal value between 0 and 1.

Events

The SDK will emit events to our browser to notify about changes to its internal state. We can use the addListener method to listen and subscribe to those events. You can find detailed information about the events supported by the SDK on the SDK reference page

The first two events we want to get notified are ready, emitted when the SDK is connected and ready to stream content, and not_ready, in case the connection is broken. In the following example, we will print them out on console once the events are received:

  // Ready
  player.addListener('ready', ({ device_id }) => {
    console.log('Ready with Device ID', device_id);
  });

  // Not Ready
  player.addListener('not_ready', ({ device_id }) => {
    console.log('Device ID has gone offline', device_id);
  });

Let’s add some listeners to get notified in case something happens during the SDK initialization:

  player.addListener('initialization_error', ({ message }) => { 
      console.error(message);
  });

  player.addListener('authentication_error', ({ message }) => {
      console.error(message);
  });

  player.addListener('account_error', ({ message }) => {
      console.error(message);
  });

Finally, let’s call connect method to perform the connection of our new Spotify instance:

  player.connect();

At that point you should have initialized and connected a new player called Web Playback SDK Quick Start Player in Spotify Connect. You can also check the JavaScript console to see the messages emitted by the SDK events.

Controlling playback

The Web Playback SDK allows you to control playback so let’s add a button to enable users to toggle play. Let’s add a button:

<button id="togglePlay">Toggle Play</button>

Inside the onSpotifyWebPlaybackSDKReady method we can add an onclick listener and have it interact with the Player object:

document.getElementById('togglePlay').onclick = function() {
  player.togglePlay();
};

You can see a list of all the playback controls available in the Web Playback API Reference.

Mobile support

Safari on iOS and other mobile browsers have restrictions for autoplay behaviour. When the SDK initializes, and playback is transferred via Spotify Connect the browser sees the command as coming from Spotify servers and not from the user, which will be classified as autoplay behaviour and often gets blocked.

To work around this limitation, the user needs to interact with the SDK to trigger media activation. Adding a button that calls togglePlay() or resume() should be enough.

Listening through the SDK

To play a track inside your browser, connect to the Web Playback SDK Quick Start Player player using another Spotify client. Then play a song and you should hear it playing in your browser. If you’re testing on a mobile browser you may have to click the Toggle Play button.

Spotify Connect

Congratulations! You’ve interacted with the Web Playback SDK for the first time. Time to celebrate, you did a great job! 👏

Want more? Here’s what you can do next:

Source Code

For your convenience, here is the full source code of the example:


<!DOCTYPE html>
<html>
<head>
    <title>Spotify Web Playback SDK Quick Start</title>
</head>
<body>
    <h1>Spotify Web Playback SDK Quick Start</h1>
    <button id="togglePlay">Toggle Play</button>

    <script src="https://sdk.scdn.co/spotify-player.js"></script>
    <script>
        window.onSpotifyWebPlaybackSDKReady = () => {
            const token = '[My access token]';
            const player = new Spotify.Player({
                name: 'Web Playback SDK Quick Start Player',
                getOAuthToken: cb => { cb(token); },
                volume: 0.5
            });

            // Ready
            player.addListener('ready', ({ device_id }) => {
                console.log('Ready with Device ID', device_id);
            });

            // Not Ready
            player.addListener('not_ready', ({ device_id }) => {
                console.log('Device ID has gone offline', device_id);
            });

            player.addListener('initialization_error', ({ message }) => {
                console.error(message);
            });

            player.addListener('authentication_error', ({ message }) => {
                console.error(message);
            });

            player.addListener('account_error', ({ message }) => {
                console.error(message);
            });

            document.getElementById('togglePlay').onclick = function() {
              player.togglePlay();
            };

            player.connect();
        }
    </script>
</body>
</html>