Search code examples
javascripttypescriptnext.jsspotify

Get Spotify Token and display info in next.js


Simple Next.js component that displays currently playing song on Spotify.

Context:
Using app Router

Since, to get token, Spotify requires me to make a serverside call, hence I'm making the complete request to fetch song from a API endpoint localhost/api/player

const getAccessToken = async () => {
  const client_id = 'key'; // Replace with your client ID
  const client_secret = 'key'; // Replace with your 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:

enter image description here

Unhandled Runtime Error

Error: The default export is not a React Component in page: "/api/player"

I tried to run this on clientside, but Spotify doesn't allow fetching tokens on client side.
I just want to get serversideprops from server about the currently playing song every 5 seconds, or the best way to display currently playing song.


Solution

  • Context: using app Router

    you probably named the file name as page.ts inside api folder. your structure is like this

     app/api/get-token/page.ts
    

    api files are named route.ts. you should have

     app/api/get-token/route.ts