Realtime Spotify API

a year ago
15-03-2023
1 min read
183 words
SPOTIFY_CLIENT_ID=
SPOTIFY_CLIENT_SECRET=
SPOTIFY_REFRESH_TOKEN=

You can get your client ID and secret from the Spotify Developer Dashboard. And you can get your refresh token by following the Authorization Guide.

import querystring from "querystring";

const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN;

const basic = Buffer.from(client_id + ":" + client_secret).toString("base64");
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
const PLAYBACK_STATE_ENDPOINT = `https://api.spotify.com/v1/me/player`;

const getAccessToken = async () => {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: querystring.stringify({
      grant_type: "refresh_token",
      refresh_token,
    }),
  });

  return response.json();
};

The rest is just frontend code. I use Next.js for my website, so I have an API route that returns the current song I am listening to.

Comments
Loading

Calculating the meaning of life... Please wait.