Snippet
Spotify Currently Playing
Display the song currently playing on your Spotify account
A useful JavaScript code snippet, using Spotify's APIs to fetch the currently playing track on your Spotify account. This example uses Next.js API Routes.
1// /lib/spotify.js
2const client_id = process.env.SPOTIFY_CLIENT_ID
3const client_secret = process.env.SPOTIFY_CLIENT_SECRET
4const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN
5
6const getAccessToken = async () => {
7 const response = await fetch('https://accounts.spotify.com/api/token', {
8 method: 'POST',
9 headers: {
10 Authorization: `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
11 'Content-Type': 'application/x-www-form-urlencoded'
12 },
13 body: new URLSearchParams({
14 grant_type: 'refresh_token',
15 refresh_token: refresh_token
16 })
17 })
18
19 return response.json()
20}
21
22export const getNowPlaying = async () => {
23 const { access_token } = await getAccessToken()
24
25 return fetch('https://api.spotify.com/v1/me/player/currently-playing', {
26 headers: {
27 Authorization: `Bearer ${access_token}`
28 }
29 })
30}
31
1// /api/currently-playing.js
2import { getNowPlaying } from '#/lib/spotify'
3
4export default async function handler(req, res) {
5 const response = await getNowPlaying()
6
7 if (response.status === 204 || response.status > 400) {
8 return res.status(200).json({ isPlaying: false })
9 }
10
11 const song = await response.json()
12
13 if (song.item === null) {
14 return res.status(200).json({ isPlaying: false })
15 }
16
17 const isPlaying = song.is_playing
18 const title = song.item.name
19 const artist = song.item.artists.map((_artist) => _artist.name).join(', ')
20 const album = song.item.album.name
21 const albumImageUrl = song.item.album.images[0].url
22 const songUrl = song.item.external_urls.spotify
23
24 return res.status(200).json({
25 album,
26 albumImageUrl,
27 artist,
28 isPlaying,
29 songUrl,
30 title
31 })
32}
33
The `spotify.js` file contains a function called `getNowPlaying` that gets the user's access token for Spotify and uses it to fetch the currently playing song using the Spotify Web API. It returns the fetched data as a Promise.
The `currently-playing.js` file is an API route that calls the `getNowPlaying` function from the `spotify.js file`. It then checks whether the response from the API call is valid and contains a playing song. If it does, it returns a JSON object containing information about the song such as its title, artist, album, album image, and URL. If there is no currently playing song, it returns a JSON object indicating that there is no song playing.
Together, these components provide a way to display information about the currently playing song on a user's Spotify account.