---
heading: 'Display Spotify currently playing track'
title: "How to work with Spotify's API to display currently playing track on a website?"
date: '2023-04-06'
icon: 'Spotify'
draft: false
summary: 'Retrieve a Spotify access token to display the currently playing track on your website or application.'
tags: [spotify, nowplaying, spotify-api, nextjs]
---

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](https://developer.spotify.com/dashboard/applications) 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](/static/images/spotify-app.png)

## Authentication

Since we only need to generate the token once, we will use the [Authorization Code Flow](https://developer.spotify.com/documentation/web-api/concepts/authorization#authorization-code-flow).
Navigate to the following URL and replace the `CLIENT_ID` with your Spotify app `Client ID`:

```bash
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](/static/images/spotify-auth.png)

After the authentication process, you will be redirected to the redirect URI with a `code` query parameter.
The redirect URI will look like this:

```bash
http://localhost:3434/?code=a1b2c...i9j0
```

![Spotify code](/static/images/spotify-code.png)

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:

```js:spotify.js {3,18} showLineNumbers
let data = {
  grant_type: 'authorization_code',
  code: 'AQB....GemX',
  redirect_uri: 'http://localhost:3434',
}

let formData = []
for (let prop in data) {
  let encodedKey = encodeURIComponent(prop)
  let encodedValue = encodeURIComponent(data[prop])
  formData.push(encodedKey + '=' + encodedValue)
}
formData = formData.join('&')

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: formData,
})
```

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

Replace the `<base64 encoded client_id:client_secret>` in line 18 with the base64 encoded value of your Spotify app `Client ID` and `Client secret`.
You can use this [online tool](https://www.base64encode.org/) to encode the value.

![Base64 encode tool](/static/images/spotify-base64-encode.png)

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.

## Querying the nowplaying 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:

```js:spotify.js showLineNumbers
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.

```bash:.env showLineNumbers
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 playing! <Twemoji emoji="clinking-beer-mugs" />
