Github
Share

Now Playing integrations with music streaming platforms like Spotify have become increasingly popular, offering users a seamless way to share their current favorite tracks with others. In this tutorial, we'll walk through building a Now Playing feature using Next.js and TypeScript, focusing on its integration with the Spotify API.
Before diving into the implementation, make sure you have the following:
The first step is done! Now, you need to do authentication to get access & refresh token.
To do authentication, we need to prepare CLIENT_ID and put it into this link below:
javascripthttps://accounts.spotify.com/authorize?client_id=YOUR CLIENT_ID_HERE&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:3000&scope=user-read-currently-playing
example:
Replace “YOUR CLIENT_ID_HERE” with the client Id.
javascripthttps://accounts.spotify.com/authorize?client_id=eaccb97f6d0e405897adf1dd80b95c01&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:3000&scope=user-read-currently-playing
Open that link in a browser, then you will get redirected into a url, copy the website link
The code after (=) is the one you currently have. Remember to write it down.
Next, we must obtain an authorized client that has previously undergone base64 encryption. To do so, utilize this website to encrypt in the client_id:client_secret format.
Next, copy the base64 encryption.
Next, launch this command in terminal/cmd, making sure to replace the code and base64 with your own.
javascriptcurl -H "Authorization: Basic CHANGE_BASE64_HERE"-d grant_type=authorization_code -d code=CHANGE_CODE_HERE -d redirect_uri=http%3A%2F%2Flocalhost:3000
Example:
javascriptcurl -H "Authorization: Basic ZWFjY2I5N2Y2ZDBlNDA1ODk3YWRmMWRkODBiOTVjMDE6YTQxOTVjMmQwYTQyNDM2MDllNjk3ZTYwMmU3MGI3NjI=" -d grant_type=authorization_code -d code=AQBeA9SD7QbA9hUfv_TfmatYxT51CY87msMnOZmMbhf7ZaxfbvG7oKEsATOJBxDyFap0Aq6uftY0v4Hq1QSy3MgQBfAHhmrifty-62rfDRlFnd0AzXRBOMpoOSA6SNw_uTPp7AixAE5zosgiIIf7efhzf1QOJfLh1HUYi248z8jk1x2jjKG2YLvMyJuP0rjB5tP5UHjoFGBvKbULpchkF6yiJHnS -d redirect_uri=http%3A%2F%2Flocalhost:3000 https://accounts.spotify.com/api/token
You will get a JSON like this:
javascript{ "access_token": "BQDKxO7h1I1wA3esGK9zCFWn97XORJEPjwAHAEIxCnDXcmy9GbEuPacquwWvpiM4d33gJVHVOP9KUxY8AXkpXc-_zRFZBfneHM2vEeV1Fbfr-0Mw94oimlNf77dRiyxPpm4IUVNLloUWgYcfkAO0","token_type": "Bearer","expires_in": 3600,"refresh_token": "AQAtxXvnzRTt4c2-2_Av2WyJQKWxUW_hMVN6QNiqv2i8A2ZElVarmvdhqyc8Pf-Z5n827FTFxTpHq5E3kOsrlRWM3TuJWxjVQsW0icR0zo3BXRFLt2FB2Qfj-pFaZwY-qc8","scope": "user-read-currently-playing"}
javascriptnpm install axios dotenv querystring @types/axios @types/dotenv @types/querystring
Create an API route . inside /pages/api/spotify.ts
javascriptimport axios from 'axios';import { NextApiRequest, NextApiResponse } from 'next';import querystring from 'querystring';const {SPOTIFY_CLIENT_ID: client_id,SPOTIFY_CLIENT_SECRET: client_secret,SPOTIFY_REFRESH_TOKEN: refresh_token,} = process.env;const token = Buffer.from(`${client_id}:${client_secret}`).toString('base64');const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`;const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;interface SpotifyData {is_playing: boolean;item: {name: string;album: {name: string;artists: Array<{ name: string }>;images: [{ url: string }];};external_urls: {spotify: string;};};currently_playing_type: string;}const getAccessToken = async () => {const res = await axios.post<{ access_token: string }>(TOKEN_ENDPOINT,querystring.stringify({grant_type: 'refresh_token',refresh_token,}),{headers: {Authorization: `Basic ${token}`,'Content-Type': 'application/x-www-form-urlencoded',},});return res.data.access_token;};export const getNowPlaying = async () => {const access_token = await getAccessToken();return axios.get<SpotifyData>(NOW_PLAYING_ENDPOINT, {headers: {Authorization: `Bearer ${access_token}`,},});};export default async function spotify(req: NextApiRequest,res: NextApiResponse) {if (req.method === 'GET') {const response = await getNowPlaying();if (response.status === 204 ||response.status > 400 ||response.data.currently_playing_type !== 'track') {//? s-maxage=180 because song usually lasts 3 minutesres.setHeader('Cache-Control','public, s-maxage=180, stale-while-revalidate=90');return res.status(200).json({ isPlaying: false });}const data = {isPlaying: response.data.is_playing,title: response.data.item.name,album: response.data.item.album.name,artist: response.data.item.album.artists.map((artist) => artist.name).join(', '),albumImageUrl: response.data.item.album.images[0].url,songUrl: response.data.item.external_urls.spotify,};console.log(data)res.setHeader('Cache-Control','public, s-maxage=180, stale-while-revalidate=90');return res.status(200).json(data);}}
Environment variables: Create a .env file in the root directory of your project and store your Spotify API credentials:
SWR is one tool we may use to retrieve data. One excellent library that can regularly retrieve the API is SWR. Every time we focused on the window, SWR will do refetching.
javascriptnpm i swr
Create the "spotify.tsx" component and add this code, or add the following code to the index.ts file.
javascriptimport React from 'react';import axios from 'axios';import { SiSpotify } from 'react-icons/si';import useSWR from 'swr';interface SpotifyData {isPlaying: boolean;songUrl: string;albumImageUrl: string;title: string;artist: string;album: string;}const fetcher = (url: string) => axios.get(url).then((res) => res.data);const SpotifyCard: React.FC = () => {const { data, error } = useSWR<SpotifyData>('/api/spotify', fetcher);if (error) {console.log(error);}return (<div ><atarget='_blank'rel='noreferrer'href={data?.isPlaying ? data.songUrl : 'https://open.spotify.com'}><div >{data?.isPlaying ? (<img ' src={data?.albumImageUrl} alt={data?.album} />) : (<SiSpotify size={30} color={'#1ED760'} />)}</div><div><p >{data?.isPlaying ? <p>{data.title}</p> : 'Currently not listening'}</p><p >{data?.isPlaying ? `Artist: ${data.artist}` : 'Spotify'}</p><p >{data?.isPlaying ? `Album: ${data.album}` : ''}</p></div><div >{data?.isPlaying ? <SiSpotify size={20} color={'#1ED760'} /> : <></>}</div></a></div>);};export default SpotifyCard;
You can check out the how i added it to my blog
https://github.com/priyez/Blog/blob/master/layouts/Spotify.tsx
In this tutorial, we've created a Now Playing feature using Next.js and TypeScript, integrating it with the Spotify API. Users can now see what track is currently playing on their Spotify account within our application. This implementation can be further expanded to include additional features such as playback controls, playlist integration, and more. Happy coding!