How to work with Spotify's API to display currently playing track on a website?
- Published on
- Published on
- /4 mins read/---
If you want to display your Spotify now playing track on your website, you need to get a token from Spotify. This token will be used to get the track information from Spotify API.
Create a Spotify app
First, you need to create a Spotify app to get the credentials in order to generate the token.
- Go to Spotify for Developers and login with your Spotify account.
- Click on Create app button.
- Fill the form and with the app name and description.
- Add a redirect URI. This URI will be used to redirect to your local app after the authentication. For example,
http://localhost:3434
. - Click on Create button.
After creating the app, navigate to the Settings page and copy the Client ID
and Client secret
. We will use these values in the next step.
Authentication
Since we only need to generate the token once, we will use the Authorization Code Flow. Navigate to the following URL and replace the CLIENT_ID
with your Spotify app Client ID
:
Remember to use the same redirect URI that you added to your Spotify app. In my case, it's http://localhost:3434
.
After the authentication process, you will be redirected to the redirect URI with a code
query parameter. The redirect URI will look like this:
Save this code
value, we will use it in the next step.
Next step is to send a POST request to the Spotify API to get the token. We'll simply open a new tab in the browser and send the request using the fetch
API in the browser developer tools.
Run this code in the Console tab of the browser developer tools:
Replace the code in line 3 with the code
value that you saved in the previous step.
Replace the <base64 encoded client_id:client_secret>
in line 18 with the base64 encoded value of your Spotify app Client ID
and Client secret
. You can use this online tool to encode the value.
The value format should be client_id:client_secret
The request will return a response containing a refresh_token
, this token is valid indefinitely unless you revoke it or you change the password of your Spotify account.
Querying the nowplaying track
Now that we have the token, we can use it to fetch the now playing track from Spotify API. Use this code to fetch the now playing track in your node server:
Remember to add the required environment variables to your .env
file.
That's it! Now you can use the getNowPlaying
function to fetch the now playing track from Spotify API.
Happy playing!