npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

lastfm-client-ts

v3.1.1

Published

A universal Last.fm API client for Node.js and Browser

Downloads

65

Readme

lastfm-client-ts

NPM Version Downloads Per Week License: MIT

A universal Last.fm API client for Node.js and Browser, written in TypeScript.

Features

  • Universal: Works in Node.js (≥20.0.0) and Browser
  • TypeScript: Full type safety with comprehensive type definitions
  • Zod Schemas: Runtime validation schemas for all types
  • ESM: Modern ES modules with tree-shaking support
  • Flexible: Global configuration or per-instance configuration
  • Modular: Import only what you need
  • Minimal Dependencies: Only js-md5 for API signatures and zod for runtime validation

Table of Contents

Installation

npm install lastfm-client-ts

Requirements:

  • Node.js ≥ 20.0.0 (for native fetch support)
  • Modern browsers with fetch API support

Quick Start

import { LastFmClient } from 'lastfm-client-ts';

// Create a client instance
const client = new LastFmClient({
  apiKey: 'YOUR_API_KEY'
});

// Fetch user information
const userInfo = await client.user.getInfo({ user: 'ansango' });
console.log(userInfo);

// Search for albums
const albums = await client.album.search({ album: 'Believe' });
console.log(albums);

Usage

Using the Client Class (Recommended)

The client class provides access to all API services in one place:

import { LastFmClient } from 'lastfm-client-ts';

const client = new LastFmClient({
  apiKey: 'YOUR_API_KEY',
  sharedSecret: 'YOUR_SHARED_SECRET', // Optional, required for authenticated methods
  sessionKey: 'USER_SESSION_KEY'      // Optional, required for user-specific methods
});

// User service
const userInfo = await client.user.getInfo({ user: 'ansango' });
const topArtists = await client.user.getTopArtists({ user: 'ansango', period: '7day' });

// Album service
const albumInfo = await client.album.getInfo({ artist: 'Cher', album: 'Believe' });
const albumSearch = await client.album.search({ album: 'Believe', limit: 10 });

// Artist service
const artistInfo = await client.artist.getInfo({ artist: 'Radiohead' });
const similarArtists = await client.artist.getSimilar({ artist: 'Radiohead' });

// Track service
const trackInfo = await client.track.getInfo({ artist: 'The Beatles', track: 'Yesterday' });
const trackSearch = await client.track.search({ track: 'Yesterday', limit: 10 });

// Chart service
const topChartArtists = await client.chart.getTopArtists();
const topChartTracks = await client.chart.getTopTracks();

// Tag service
const tagInfo = await client.tag.getInfo({ tag: 'rock' });
const topTagArtists = await client.tag.getTopArtists({ tag: 'rock' });

// Geo service
const topArtistsByCountry = await client.geo.getTopArtists({ country: 'spain' });

// Library service
const libraryArtists = await client.library.getArtists({ user: 'ansango' });

// Auth service (for scrobbling and authenticated methods)
const session = await client.auth.getSession({ token: 'AUTH_TOKEN' });

Using Global Configuration

Set configuration globally and reuse it across multiple client instances:

import { setGlobalConfig, createClient } from 'lastfm-client-ts';

// Set global configuration once
setGlobalConfig({
  apiKey: process.env.LASTFM_API_KEY!,
  sharedSecret: process.env.LASTFM_SHARED_SECRET
});

// Create clients without passing config
const client1 = createClient();
const client2 = createClient();

// Both clients use the same global configuration
const user1 = await client1.user.getInfo({ user: 'user1' });
const user2 = await client2.user.getInfo({ user: 'user2' });

Using Individual Services

Import only the services you need for better tree-shaking:

// Import only the user service
import { createUserService } from 'lastfm-client-ts/user';
import type { UserGetInfoRequest } from 'lastfm-client-ts/user';

const userService = createUserService({
  apiKey: 'YOUR_API_KEY'
});

const params: UserGetInfoRequest = { user: 'ansango' };
const userInfo = await userService.getInfo(params);
// Import multiple services
import { createAlbumService } from 'lastfm-client-ts/album';
import { createTrackService } from 'lastfm-client-ts/track';

const config = { apiKey: 'YOUR_API_KEY' };

const albumService = createAlbumService(config);
const trackService = createTrackService(config);

const albums = await albumService.search({ album: 'Abbey Road' });
const tracks = await trackService.search({ track: 'Come Together' });

Available service imports:

  • lastfm-client-ts/user
  • lastfm-client-ts/album
  • lastfm-client-ts/artist
  • lastfm-client-ts/track
  • lastfm-client-ts/tag
  • lastfm-client-ts/chart
  • lastfm-client-ts/geo
  • lastfm-client-ts/library
  • lastfm-client-ts/auth

Zod Schema Validation

The library includes automatically generated Zod schemas for runtime validation. These schemas mirror all TypeScript types and can be used to validate API responses or user input at runtime.

Importing Schemas

Schemas are available through modular imports, following the same pattern as the services:

import { userGetInfoRequestSchema, userGetInfoResponseSchema } from 'lastfm-client-ts/user/schemas';
import { albumSearchRequestSchema } from 'lastfm-client-ts/album/schemas';
import { trackGetInfoResponseSchema } from 'lastfm-client-ts/track/schemas';

Usage Example

import { userGetInfoRequestSchema, userGetInfoResponseSchema } from 'lastfm-client-ts/user/schemas';

// Validate request parameters
const params = { user: 'ansango' };
const validatedParams = userGetInfoRequestSchema.parse(params);

// Validate API response
const response = await fetch(`https://ws.audioscrobbler.com/2.0/...`);
const data = await response.json();
const validatedData = userGetInfoResponseSchema.parse(data);

// Safe parsing (doesn't throw)
const result = userGetInfoResponseSchema.safeParse(data);
if (result.success) {
  console.log(result.data);
} else {
  console.error(result.error);
}

Available schema imports:

  • lastfm-client-ts/user/schemas
  • lastfm-client-ts/album/schemas
  • lastfm-client-ts/artist/schemas
  • lastfm-client-ts/track/schemas
  • lastfm-client-ts/tag/schemas
  • lastfm-client-ts/chart/schemas
  • lastfm-client-ts/geo/schemas
  • lastfm-client-ts/library/schemas
  • lastfm-client-ts/auth/schemas
  • lastfm-client-ts/schemas (base types like imageSchema, datePropSchema, etc.)

Environment Variables

In Node.js environments, the client automatically loads configuration from environment variables:

# .env file
LASTFM_API_KEY=your_api_key_here
LASTFM_SHARED_SECRET=your_shared_secret_here
LASTFM_SESSION_KEY=user_session_key_here

# Optional: Custom base URL
LASTFM_BASE_URL=https://ws.audioscrobbler.com/2.0/
// Configuration is loaded automatically from process.env
import { createClient } from 'lastfm-client-ts';

const client = createClient(); // Uses environment variables

Browser Usage:

In browser environments, pass configuration explicitly or use your bundler's environment variable system:

// Vite
const client = new LastFmClient({
  apiKey: import.meta.env.VITE_LASTFM_API_KEY
});

// Webpack
const client = new LastFmClient({
  apiKey: process.env.REACT_APP_LASTFM_API_KEY
});

API Reference

Client

The main client class with all services:

class LastFmClient {
  user: UserService;
  album: AlbumService;
  artist: ArtistService;
  track: TrackService;
  tag: TagService;
  chart: ChartService;
  geo: GeoService;
  library: LibraryService;
  auth: AuthService;
  
  constructor(config?: Partial<LastFmConfig>);
  getConfig(): Readonly<LastFmConfig>;
}

Configuration

interface LastFmConfig {
  apiKey: string;           // Required: Your Last.fm API key
  sharedSecret?: string;    // Optional: Required for authenticated methods
  sessionKey?: string;      // Optional: User session key for scrobbling
  baseUrl?: string;         // Optional: API base URL (default: https://ws.audioscrobbler.com/2.0/)
}

// Configuration functions
function createConfig(options?: Partial<LastFmConfig>): LastFmConfig;
function setGlobalConfig(config: Partial<LastFmConfig>): void;
function getGlobalConfig(): LastFmConfig;
function resetGlobalConfig(): void;

Services

Each service provides methods for interacting with specific Last.fm API endpoints:

  • UserService: User-related methods (getInfo, getTopArtists, getRecentTracks, etc.)
  • AlbumService: Album methods (getInfo, search, getTags, etc.)
  • ArtistService: Artist methods (getInfo, getSimilar, getTopAlbums, etc.)
  • TrackService: Track methods (getInfo, search, scrobble, etc.)
  • TagService: Tag methods (getInfo, getTopArtists, getTopTracks, etc.)
  • ChartService: Chart methods (getTopArtists, getTopTracks, etc.)
  • GeoService: Geographic methods (getTopArtists, getTopTracks by country)
  • LibraryService: Library methods (getArtists, etc.)
  • AuthService: Authentication methods (getSession, etc.)

TypeScript Support

The library is fully typed with comprehensive TypeScript definitions:

import { LastFmClient } from 'lastfm-client-ts';
import type {
  UserGetInfoRequest,
  UserGetInfoResponse,
  AlbumSearchRequest,
  AlbumSearchResponse
} from 'lastfm-client-ts';

const client = new LastFmClient({ apiKey: 'YOUR_API_KEY' });

// Type-safe requests and responses
const userParams: UserGetInfoRequest = { user: 'ansango' };
const userInfo: UserGetInfoResponse = await client.user.getInfo(userParams);

const albumParams: AlbumSearchRequest = { album: 'Believe', limit: 10 };
const albums: AlbumSearchResponse = await client.album.search(albumParams);

All request parameters and response types are exported for your convenience.

Contributing

Contributions are always welcome!

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes using Conventional Commits
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Scripts

# Install dependencies
bun install

# Run in development mode (watch mode)
bun run dev

# Build the project
bun run build

# Run tests
bun test

# Clean build artifacts
bun run clean

Release Process

This project uses automated release scripts:

# Create a patch release (1.0.0 -> 1.0.1)
bun run release:patch

# Create a minor release (1.0.0 -> 1.1.0)
bun run release:minor

# Create a major release (1.0.0 -> 2.0.0)
bun run release:major

# Create an alpha release (1.0.0 -> 1.0.1-alpha.0)
bun run release:alpha

# Create a beta release (1.0.0 -> 1.0.1-beta.0)
bun run release:beta

The release script will:

  • Run tests
  • Build the project
  • Generate changelog from commits
  • Bump version in package.json
  • Create git tag
  • Create GitHub release
  • Publish to npm

For more details, see scripts/README.md.

License

MIT © Anibal Santos