Spotify Live Audio
How I leveraged Spotify's API to create a Currently Playing Component for my website.
10 Aug 2024You may have noticed the Spotify tile in the bottom left corner of the page. This tile shows what I'm currently listening to on Spotify, and it updates in real-time. Here's how I built it.
Overview
Tools
- Spotify API: I used the Spotify Web API to fetch the currently playing track. (It's free!)
- Next.js: I used Next.js to create the API route that fetches the currently playing track from Spotify.
- Express: I used Express to create a simple server that serves the API route.
Implementation
- Create a Spotify Developer Account: Go to the Spotify Developer Dashboard and create a new application. This will give you the Client ID and Client Secret needed to access the Spotify API.
- Set Up the Express Routes: Add the right middleware to stop unauthorized users from spamming the API on your behalf.
import { writeFile, readFile } from "fs/promises";
import express, { Request, Response } from 'express';
require('dotenv').config();
const axios = require('axios');
const querystring = require('querystring');
const app = express();
const PORT = 3500;
const { SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URI } = process.env;
async function getTokens() : Promise<{access_token: string, refresh_token: string}> {
return JSON.parse(await readFile('access_token', 'utf-8'))
}
async function setToken(tokens: {access_token?: string, refresh_token: string}|{access_token: string, refresh_token?: string}) {
await writeFile('access_token', JSON.stringify({...await getTokens(), ...tokens}))
}
app.use((req, res, next) => {
console.log(req.path)
if (req.headers["authorization"] == "Bearer c2VjcmV0c2VjcmV0" || ["/login", "/callback"].includes(req.path)){
return next()
}
res.status(401).json({error: "Unauthorized"})
});
app.get('/login', (req, res) => {
const scope = 'user-read-playback-state user-read-currently-playing';
const queryParams = querystring.stringify({
response_type: 'code',
client_id: SPOTIFY_CLIENT_ID,
scope,
redirect_uri: SPOTIFY_REDIRECT_URI,
});
console.log(queryParams)
const authUrl = `https://accounts.spotify.com/authorize?${queryParams}`;
res.redirect(authUrl);
});
app.get('/callback', async (req, res) => {
const code = req.query.code || null;
try {
const response = await axios.post(
'https://accounts.spotify.com/api/token',
querystring.stringify({
grant_type: 'authorization_code',
code,
redirect_uri: SPOTIFY_REDIRECT_URI,
client_id: SPOTIFY_CLIENT_ID,
client_secret: SPOTIFY_CLIENT_SECRET,
}),
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}
);
await writeFile('access_token', JSON.stringify(response.data))
res.json({
ok: "ok",
});
} catch (error) {
//@ts-ignore
console.error('Error fetching access token:', error.response?.data || error.message);
res.status(500).send('Error during Spotify authorization');
}
});
app.get('/token', async (req, res) => {
let tokens = await getTokens()
if (!tokens.access_token) {
res.status(401).send('User is not authenticated with Spotify');
return;
}
res.json({ access_token: tokens.access_token });
});
app.get('/refresh-token', async (req, res) => {
let tokens = await getTokens()
if (!tokens.refresh_token) {
res.status(401).send('No refresh token available');
return
}
try {
const response = await axios.post(
'https://accounts.spotify.com/api/token',
querystring.stringify({
grant_type: 'refresh_token',
refresh_token: tokens.refresh_token,
client_id: SPOTIFY_CLIENT_ID,
client_secret: SPOTIFY_CLIENT_SECRET,
}),
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}
);
setToken({ access_token: response.data.access_token })
res.json({ access_token: response.data.access_token });
} catch (error) {
console.error('Error refreshing token:', error.response?.data || error.message || error);
res.status(500).send('Error refreshing Spotify token');
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- Set Up the API Route: In your Next.js application, create a new API route that will handle the request to your API. [1]
const getAccessToken = async (refresh?: boolean) : Promise<{access_token : string}> => {
let res;
if (refresh) {
res = await fetch("https://your-server.example/refresh-token", {
headers : {
"Authorization" : `Bearer ${process.env.API_KEY}`
},
cache : "no-store"
});
}
else {
res = await fetch("https://your-server.example/token", {
headers : {
"Authorization" : `Bearer ${process.env.API_KEY}`
},
cache : "no-store"
});
}
return await res.json();
};
export const revalidate = false;
export const runtime = 'edge';
export async function GET(){
let spotify;
try {
spotify = await ((await fetch("https://api.spotify.com/v1/me/player/currently-playing?market=DE", {
headers: {
Authorization: `Bearer ${(await getAccessToken(false)).access_token}`,
},
cache : "no-store"
}))).json()
if (spotify.error?.status == 401){
throw "401"
}
}
catch {
try {
spotify = (await fetch("https://api.spotify.com/v1/me/player/currently-playing?market=DE", {
headers: {
Authorization: `Bearer ${(await getAccessToken(true)).access_token}`,
},
cache : "no-store"
}))
if (spotify.status == 204){
return Response.json({data : null, status : "np"})
}
}
catch {
return Response.json({data : null, status : "error"}, {status : 500})
}
}
return Response.json({data : spotify, status : spotify.status})
};
Code should be pretty self-explanatory. Let me know if you need help implementing this!
Footnotes
[1] : Notice how I said your API and not Spotify's? That is intentional. First, It's good practice to route requests through an endpoint you control. Second, it's accessing the Spotify API on your account's behalf, so you don't want to be exposing your access_token to just about anyone.
