Getting Spotify token to display now playing track on your website

Published on
4 mins read
––– views

If you want to display your Spotify now playing track on your website, you need to get a token from Spotify. This token will be used to get the track information from Spotify API.

Create a Spotify app

First, you need to create a Spotify app to get the credentials in order to generate the token.

  • Go to Spotify for Developers and login with your Spotify account.
  • Click on Create app button.
  • Fill the form and with the app name and description.
  • Add a redirect URI. This URI will be used to redirect to your local app after the authentication. For example, http://localhost:3434.
  • Click on Create button.

After creating the app, navigate to the Settings page and copy the Client ID and Client secret. We will use these values in the next step.

Spotify App

Authentication

Since we only need to generate the token once, we will use the Authorization Code Flow.

Navigate to the following URL and replace the CLIENT_ID with your Spotify app Client ID:

https://accounts.spotify.com/authorize?client_id=CLIENT_ID&response_type=code&redirect_uri=http://localhost:3434&scope=user-read-currently-playing

Remember to use the same redirect URI that you added to your Spotify app.

In my case, it's http://localhost:3434.

Spotify auth

After the authentication process, you will be redirected to the redirect URI with a code query parameter.

The redirect URI will look like this:

http://localhost:3434/?code=a1b2c...i9j0
Spotify code

Save this code value, we will use it in the next step.

Next step is to send a POST request to the Spotify API to get the token. We'll simply open a new tab in the browser and send the request using the fetch API in the browser developer tools.

Run this code in the Console tab of the browser developer tools:

fetch('https://accounts.spotify.com/api/token', {
  method: 'POST',
  headers: {
    Authorization: 'Basic <base64 encoded client_id:client_secret>',
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: JSON.stringify({
    grant_type: 'authorization_code',
    code: 'a1b2c...i9j0',
    redirect_uri: 'http://localhost:3434',
  }),
})

Replace the code in line 9 with the code value that you saved in the previous step.

Replace the base64 encoded client_id:client_secret in line 4 with the base64 encoded value of your Spotify app Client ID and Client secret. You can use this online tool to encode the value.

Base64 encode tool

The value format should be client_id:client_secret.

The request will return a response containing a refresh_token, this token is valid indefinitely unless you revoke it or you change the password of your Spotify account.

Bonus: fetching the now playing track

Now that we have the token, we can use it to fetch the now playing track from Spotify API.

Use this code to fetch the now playing track in your node server:

import fetch from 'isomorphic-unfetch'

let SPOTIFY_TOKEN_API = `https://accounts.spotify.com/api/token`
let SPOTIFY_NOW_PLAYING_API = `https://api.spotify.com/v1/me/player/currently-playing`
let SPOTIFY_TOP_TRACKS_API = `https://api.spotify.com/v1/me/top/tracks`

let {
  SPOTIFY_CLIENT_ID: client_id,
  SPOTIFY_CLIENT_SECRET: client_secret,
  SPOTIFY_REFRESH_TOKEN: refresh_token,
} = process.env

let basic = Buffer.from(`${client_id}:${client_secret}`).toString('base64')

async function getAccessToken() {
  let response = await fetch(SPOTIFY_TOKEN_API, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${basic}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token,
    }),
  })

  return response.json()
}

export async function getNowPlaying() {
  let { access_token } = await getAccessToken()
  let url = new URL(SPOTIFY_NOW_PLAYING_API)
  url.searchParams.append('additional_types', 'track,episode')

  return fetch(url.toString(), {
    headers: {
      Authorization: `Bearer ${access_token}`,
    },
  })
}

Remember to add the required environment variables to your .env file.

SPOTIFY_CLIENT_ID=your_spotify_client_id
SPOTIFY_CLIENT_SECRET=your_spotify_client_secret
SPOTIFY_REFRESH_TOKEN=your_spotify_refresh_token

That's it! Now you can use the getNowPlaying function to fetch the now playing track from Spotify API.

Happy coding!