In this post, I will share a tutorial on getting the top tracks and currently playing on Spotify, using the Next.js API. For example, you can see the misc page.
Creating a Spotify App
We need to do this to get the credentials that will be used to authenticate the API.
Fill in the name and description then click "Create".
Click "Show Client Secret".
Save Client ID and Secret to .env file.
Click "Edit Settings".
Add http://localhost:3000 to redirect URIs.
Authentication
We need to get the authorization code by doing a request via a URL filled with the required parameters.
Please copy the URL below. Change client_id and scope as you like. Since in this tutorial we only want to read the top track and the currently playing, we only need scopeuser-top-read and user-read-currently-playing, you can read more about scope here.
After authorization, you will be redirected to your redirect_uri earlier. In the URL, there is a code query parameter. Save that value.
Next, we need a refresh_token. You have to generate a Base 64 encoded string containing the client ID and secret from earlier. You can use this tool to encode it. The format should be client_id:client_secret.
Change the command above according to your data. If so, it should be like this. (some of my data will be disguised)
After doing POST request, you will receive a JSON as below.
Using the Spotify API
We have managed to get all the necessary data. Next, create a .env.local file and fill it with the values you got earlier.
We have to request access_token using the client ID, client secret, and refresh_token we got earlier.
We will use this access_token to request top tracks. I assume you entered the user-top-read scope in the scope section earlier.
In the above code, there is a query time_range, because I want to get the top track for the past 4 weeks, so I added short_term, you can read about time_rangehere.
Creating API endpoints
First you have to create a new file in pages/api/spotify/top-tracks.js. Then import the getTopTracks function that we created earlier.
This will give you the top 10 songs that you play most frequently. You can change the code above as you wish. If you have done all the things above, you will get data like below.