Snippet: Spotify Top Tracks

Snippet

Back

Spotify Top Tracks

logo for Spotify

Fetch and display your Spotify top tracks list

This code snippet shows how you can retrieve your Spotify top tracks using Next.js API Routes.

// /lib/spotify.js
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 getAccessToken = async () => {
  const response = await fetch('https://accounts.spotify.com/api/token', {
    method: 'POST',
    headers: {
      Authorization: `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: refresh_token
    })
  })

  return response.json()
}

export const getTopTracks = async () => {
  const { access_token } = await getAccessToken()

  return fetch('https://api.spotify.com/v1/me/top/tracks?limit=5&time_range=short_term', {
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  })
}
// /api/top-tracks.js
import { getTopTracks } from '#/lib/spotify'

export default async function handler(req, res) {
  const response = await getTopTracks()
  const { items } = await response.json()

  const tracks = items.map((track) => ({
    artist: track.artists.map((_artist) => _artist.name).join(', '),
    songUrl: track.external_urls.spotify,
    title: track.name
  }))

  res.setHeader(
    "Cache-Control",
    "public, s-maxage=86400, stale-while-revalidate=43200"
  )

  return res.status(200).json(tracks)
}

The `lib/spotify.js` file contains a function `getAccessToken()` that sends a POST request to Spotify's token API endpoint, using the client ID, client secret, and refresh token provided in environment variables. The response contains an access token, which is used to send a GET request to Spotify's API endpoint to retrieve the user's top tracks for a short time period. This function is exported as `getTopTracks()`.

The `api/top-tracks.js` file imports the `getTopTracks()` function from `lib/spotify.js` and uses it to get the user's top tracks for a short time period. The API endpoint returns an array of objects, each containing the name of the artist, the name of the song, and a link to the song on Spotify. The Cache-Control header is set to cache the response for 24 hours and revalidate it after 12 hours.

Loading...

Crenshaw

Drop me a line!

©2023 Robbie Crenshaw, All Rights Reserved.