Loading Light/Dark Toggle
Spotify Now Playing now with Next js(Typescript)
In this tutorial, we've created a Now Playing feature using Next.js and TypeScript, .
Sopiriye Jamabo
Published on December 11, 2023

Github

Share

Introduction

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.

Prerequisites

Before diving into the implementation, make sure you have the following:

  • Basic knowledge of React and Next.js.
  • Understanding of TypeScript.
  • Node.js installed on your machine.
  • Spotify Developer Account (for obtaining API keys).
  • Create an Application on Spotify Developer
  • Go to Spotify Developer Website.
  • Click Create An App
  • Fill in App Name, App description, then Create an app
  • Next, you will be provided with Client ID and Client Secret (Don't give this secret to anyone).
  • Open edit settings, then fill out http://localhost:3000 on RedirectURIs.
  • The first step is done! Now, you need to do authentication to get access & refresh token.

    Authenticate Your Account

    To do authentication, we need to prepare CLIENT_ID and put it into this link below:

    javascript
    https://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.

    javascript
    https://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.

    javascript
    curl -H "Authorization: Basic CHANGE_BASE64_HERE"
    -d grant_type=authorization_code -d code=CHANGE_CODE_HERE -d redirect_uri=http%3A
    %2F%2Flocalhost:3000
    ⚠️
    "CHANGE_BASE64_HERE" is a placeholder text that indicates you should replace it with actual Base64 encoded data. Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format.

    Example:

    javascript
    curl -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"}

    Setup
  • Create a new Next.js project: If you haven't already, initiate a new Next.js project using npx create-next-app.
  • Install required dependencies: Install necessary packages like axios for making HTTP requests and dotenv for managing environment variables and querystring for parsing and formatting URL query.
  • javascript
    npm install axios dotenv querystring @types/axios @types/dotenv @types/querystring

    Create an API route . inside /pages/api/spotify.ts

    javascript
    import 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 minutes
    res.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:

    Utilize Next.js's API

    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.

    javascript
    npm i swr

    Create the "spotify.tsx" component and add this code, or add the following code to the index.ts file.

    javascript
    import 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 >
    <a
    target='_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

    Conclusion

    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!

    Subscribe
    Get an email when i write new posts and early access to new articles.
    Always Be the first to know when the article is published here ...
    Latest articles
    More articles ➜