How to get your Spotify current track

Jan 08, 2022

Table of Contents

Introduction

I saw this on Cristian Granda website and thought it was cool, had never seen it. I took two days to made it, but I will teach you how to do it fast ⚡.

After I saw the API demo , I thought ”easy-peasy”, and it really is, but getting there isn’t. Basically, you need create a Spotify integration, get a refresh token, get an auth code and then get the current track. I did get stucked on two steps: discover everything and get the refresh token. But I did find a very nice website , that makes me think I am not the only one burning the head to get a simple refresh token 😸.

How to do it

Start creating an integration in Spotify Dashboard . After, click on edit settings and add https://getyourspotifyrefreshtoken.herokuapp.com/callback on Redirect URIs.

Next, copy both client id and secret, put them at this website, mark user-read-currently-playing and submit it.

Now, you have the refresh token of your Spotify integration, use it to get an access token. I made with my personal API, using Node.js. Look the getAccessToken function:

import { stringify } from "qs";
const TOKEN_ENDPOINT = 'https://accounts.spotify.com/api/token';
const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");

const getAccessToken = async () => {
  try {
    const response = await axios.post(TOKEN_ENDPOINT, stringify({
      grant_type: "refresh_token",
      refresh_token,
    }), {
      headers: {
        Authorization: `Basic ${basic}`,
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    
    return response.data;
  } catch (error) {
    // @ts-ignore
    console.log(error.response.data); 
  }
};

Notice that I did use axios and qs packages, but you can do the same using fetch API. Finally, the function that gets the current track:

const NOW_PLAYING_ENDPOINT = 'https://api.spotify.com/v1/me/player/currently-playing?market=ES';
const getNowPlaying = async () => {
  const { access_token } = await getAccessToken();
  const res = await axios.get(NOW_PLAYING_ENDPOINT, {
    headers: {
      Authorization: `Bearer ${access_token}`,
    },
  });
  const actualMusic = await res.data;
  return actualMusic;
};

Now you have a giant JSON containing an item where have all informations about your current track. If I’m listening Spotify right now, you will see in my about page. Should be like this:

Fonts


posts Thanks for reading!