How to make a Spotify currently playing widget in React
December 10th, 2023 • 5 min read•1,400 views
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.
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.
After running the command, you'll receive a JSON response with the refresh token. Make note of the refresh_token.
Store the CLIENT_ID, CLIENT_SECRET and REFRESH_TOKEN in a .env file.
These 2 variables below are the endpoints that we'll be using.
Create a function that we'll use later on to generate an access token.
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.
Create a React component which will display the data from Spotify. This is a very basic example of periodically fetching the data.
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!