Last.fm API client with Zod runtime validation. Covers auth, now-playing, top tracks/artists/albums, recent tracks, and weekly reports. Battle-tested in BeatSphere.
npm install @beatsphere/lastfm-clientimport {
getMobileSession,
getUserInfo,
getListeningStatus,
getTopTracks,
getRecentTracks,
getWeeklyReport,
} from '@beatsphere/lastfm-client';
// You must provide an MD5 function for API signature generation.
// Examples: crypto.createHash('md5') (Node), react-native-quick-md5, js-md5, etc.
import { createHash } from 'crypto';
const md5 = (input: string) => createHash('md5').update(input).digest('hex');
// Authenticate
const { sessionKey, username } = await getMobileSession(
'YOUR_API_KEY',
'YOUR_SHARED_SECRET',
oauthToken, // from Last.fm callback URL
md5,
);
// Get user info
const user = await getUserInfo('YOUR_API_KEY', sessionKey);
// Check what someone is listening to
const status = await getListeningStatus('YOUR_API_KEY', username);
if (status) {
console.log(`${status.track.name} — ${status.status}`); // 'live' or 'recent'
}
// Top tracks
const tracks = await getTopTracks('YOUR_API_KEY', username, sessionKey, 10);
// Weekly report
const report = await getWeeklyReport('YOUR_API_KEY', username);
// { totalScrobbles: 142, uniqueArtists: 38, topArtist: { name: 'Radiohead' } }| Function | Description |
|---|---|
getMobileSession(apiKey, secret, token, md5) |
OAuth → session key. Prevents double-processing of single-use tokens |
getUserInfo(apiKey, sessionKey) |
User profile (name, playcount, image, etc.) |
getListeningStatus(apiKey, username, threshold?) |
Currently playing or recently scrobbled track |
getTopTracks(apiKey, username, sessionKey?, limit?) |
User's top tracks |
getTopArtists(apiKey, username, sessionKey?, period?, limit?) |
User's top artists |
getTopAlbums(apiKey, username, sessionKey?, period?, limit?) |
User's top albums |
getRecentTracks(apiKey, username, sessionKey?, limit?) |
Recently scrobbled tracks |
getUserRecentTrack(apiKey, username) |
Single most recent track |
getWeeklyReport(apiKey, username) |
Weekly scrobble summary |
createApiSignature(params, secret, md5) |
Generate Last.fm API signature |
For getTopArtists and getTopAlbums:
'1month'|'3month'|'6month'|'12month'|'overall'
Last.fm requires MD5-signed requests. Since MD5 implementations vary by platform, you provide your own:
// Node.js
import { createHash } from 'crypto';
const md5 = (s: string) => createHash('md5').update(s).digest('hex');
// React Native
import { stringMd5 } from 'react-native-quick-md5';
const md5 = stringMd5;
// Browser
import md5 from 'js-md5';All response schemas are exported for direct use:
import {
LastFmTrackSchema,
LastFmUserSchema,
LastFmAlbumSchema,
// ... all schemas and types
} from '@beatsphere/lastfm-client';MIT