Spotify API to get top tracks
7/9/2023, Published in Medium, DevTo and HashNode
Get top tracks for your playlist in Next.Js
import querystring from 'querystring';
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN;
const basic = Buffer.from(`${client_id}:${client_secret}`).toString('base64');
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
const TOP_TRACKS_ENDPOINT = `https://api.spotify.com/v1/me/top/tracks`;
const MY_PLAYLIST = `https://api.spotify.com/v1/playlists/3tgNxC9wZWUmOIkxZ6NtGb`;
const getAccessToken = async () => {
const response = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: querystring.stringify({
grant_type: 'refresh_token',
refresh_token,
}),
});
return response.json();
};
export const getTopTracks = async () => {
const { access_token } = await getAccessToken();
return fetch(TOP_TRACKS_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`,
},
});
};
export const getMyPlayList = async () => {
const { access_token } = await getAccessToken();
return fetch(MY_PLAYLIST, {
headers: {
Authorization: `Bearer ${access_token}`,
},
});
};
Sandeep Yaramchitti
- Bringing my ideas into life through Code.
ALL SYSTEMS ONLINE