This is a Simple Next.js component designed to display the currently playing song on Spotify.
Context:
Utilizing app Router
Due to Spotify's token requirements necessitating a server-side call, the entire request is made to fetch the song from an API endpoint localhost/api/player
const getAccessToken = async () => {
const client_id = 'key'; // Please replace with your own client ID
const client_secret = 'key'; // Please replace with your own client secret
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${btoa(`${client_id}:${client_secret}`)}`,
},
body: 'grant_type=client_credentials'
})
.then(response => response.json())
.then(data => {
console.log(data.access_token);
return data.access_token;
});
return null;
}
export const fetchCurrentPlayingSong = async () => {
const accessToken = await getAccessToken();
const response = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
if (!response.ok) {
throw new Error(`Failed to fetch currently playing song: ${response.statusText}`);
}
const song = await response.json();
return song;
};
Error:
Unhandled Runtime Error
Error: The default export is not a React Component in page: "/api/player"
Attempts were made to run this on the client side, but Spotify does not permit fetching tokens there.
The objective is to retrieve serversideprops
from the server every 5 seconds about the currently playing song,
or determine the most effective manner of displaying the currently playing song.