Spotify API Integration with Website
Spotify Web API is used for displaying current artist track, embedding players, and creating music recommendations on your website. Relevant for musician websites, podcasters, fan portals.
Authentication
Client Credentials Flow — for server requests without user participation (artist and album data):
async function getSpotifyToken(): Promise<string> {
const credentials = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');
const resp = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: { 'Authorization': `Basic ${credentials}`, 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'grant_type=client_credentials',
});
const data = await resp.json();
return data.access_token; // lives for 3600 seconds
}
Authorization Code Flow — for user data (current track, playlists).
Artist Data
async function getArtistData(artistId: string): Promise<ArtistData> {
const token = await getSpotifyToken();
const [artist, topTracks, albums] = await Promise.all([
fetch(`https://api.spotify.com/v1/artists/${artistId}`, {
headers: { Authorization: `Bearer ${token}` },
}).then(r => r.json()),
fetch(`https://api.spotify.com/v1/artists/${artistId}/top-tracks?market=RU`, {
headers: { Authorization: `Bearer ${token}` },
}).then(r => r.json()),
fetch(`https://api.spotify.com/v1/artists/${artistId}/albums?include_groups=album,single&market=RU&limit=10`, {
headers: { Authorization: `Bearer ${token}` },
}).then(r => r.json()),
]);
return {
name: artist.name,
followers: artist.followers.total,
genres: artist.genres,
popularity: artist.popularity,
image: artist.images[0]?.url,
topTracks: topTracks.tracks.slice(0, 5).map((t: any) => ({
name: t.name,
preview: t.preview_url, // 30-second MP3 preview
duration: t.duration_ms,
})),
latestAlbum: albums.items[0],
};
}
Player Embedding
<!-- Spotify Embed — no API required -->
<iframe
src="https://open.spotify.com/embed/track/TRACK_ID?utm_source=generator&theme=0"
width="100%" height="152"
frameBorder="0"
allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
loading="lazy">
</iframe>
Now Playing Widget
// Requires Authorization Code Flow + scope: user-read-currently-playing
async function getNowPlaying(userAccessToken: string) {
const resp = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
headers: { Authorization: `Bearer ${userAccessToken}` },
});
if (resp.status === 204) return null; // nothing playing
return resp.json();
}
Implementation time: 2–3 business days.







