How to make a Spotify currently playing widget in React
How to make a Spotify currently playing widget in React
December 10th, 2023•
You've reached the end. Thanks for reading!
Imagine having your current Spotify track displayed directly in React — pretty cool, right? I've included a detailed step-by-step guide below, allowing you to integrate a React component that showcases the currently playing track on your own site. Just scroll down to get started!
A refresh token is used for generating a new access token.
Replace CLIENT_ID, then copy and navigate to the URL below. The user-read-currently-playing part of the URL is a scope that is used for accessing the track that you are currently listening to.
After authorizing, you'll be redirected to the redirect URI. In the search bar, you'll see a looong code in the code search parameter. Make note of the value.
sh
http://localhost:3000/?code=YOUR_CODE
We require a base64 encoded string including the Client ID and Secret from before in the format clientid:clientsecret to generate a refresh token. You can generate the string at base64encode.org.
After encoding the string, replace YOUR_ENCODED_STRING and YOUR_CODE, then run the cURL command below at reqbin.com/curl.
Create a function that we'll use later on to generate an access token.
ts
import { TOKEN_ENDPOINT } from "path/to/file";const { CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN } = process.env;async function getAccessToken(): Promise<string> {
If using TypeScript, you can use this type below as for the Spotify currently playing response. If you want to extend this type because you think you need more types, you can go to the Spotify Developer Documentation.
Now create a function that fetches the song details from the currently playing endpoint. Please note that this function will return null if the request fails, so make sure that you implement proper error handling if you wish.
ts
async function getCurrentlyPlaying(): Promise<ISpotifyResponse | null> { try { // get the access token using the refresh token const accessToken = await getAccessToken(); // fetch the data from the currently playing endpoint using the access token const
Create a React component which will display the data from Spotify. This is a very basic example of periodically fetching the data.
tsx
import { getCurrentlyPlaying } from "path/to/file";import { useEffect, useState } from "react";export default function CurrentlyPlayingComponent() { const [
You're all set now! Congratulations on implementing the Spotify currently playing track display in your React application. Enjoy showcasing your favorite tunes on your own site. If you have any questions or feedback, feel free to reach out. Happy coding!
// encode the Client ID and Client Secret in base64