Overview
The Spotify service provides server-side integration with the Spotify Web API using OAuth2 client credentials flow. It handles authentication token management with automatic caching and expiration, and provides methods to retrieve artist top tracks. Source Location:src/server/services/spotify/
This service is designed to run exclusively on the server. Never expose authentication credentials to the client.
Authentication
getSpotifyToken()
Retrieves a valid Spotify access token using client credentials flow. Checks cache before requesting a new token to optimize API usage. Location:src/server/services/spotify/auth.ts:15
Returns
Valid Spotify access token for API requests
Authentication Flow
- Cache Check: Verifies if a valid token exists in cache
- Token Request: If cache is empty/expired, requests new token from Spotify
- Authorization: Uses Basic Auth with Base64-encoded
client_id:client_secret - Caching: Stores token in cache with 60-second buffer before expiration
API Endpoint
Request Headers
application/x-www-form-urlencodedBasic {base64(client_id:client_secret)}Request Body
Must be
client_credentialsResponse Type: SpotifyToken
Error Handling
Track Methods
getArtistTopTracks()
Retrieves the most popular tracks for a configured artist. Results are cached for 1 hour to reduce API calls. Location:src/server/services/spotify/tracks.ts:14
Parameters
No parameters required. UsesSPOTIFY_ARTIST_ID from environment configuration.
Returns
Array of track objects, or
null if error occurs or artist ID not configuredResponse Type: Track
API Endpoint
Request Headers
Bearer {access_token}Example Usage
Error Handling
Returnsnull on errors:
- Missing
SPOTIFY_ARTIST_IDenvironment variable - Authentication failures
- Network errors
- Invalid API responses
Caching Strategy
Token Caching
"spotify_token"expires_in - 60 seconds (60-second safety buffer)Track Caching
"spotify_top_tracks_{artist_id}"3600 seconds (1 hour)
Caching is implemented using
getFromCache and setInCache utilities from @/server/services/cache.Environment Variables
Spotify application client ID from Spotify Developer Dashboard
Spotify application client secret
Spotify artist ID for
getArtistTopTracks() methodError Messages
| Error | Cause | Solution |
|---|---|---|
| ”Fallo en la autenticación de Spotify” | Token request failed | Verify client credentials and network connectivity |
| ”No se ha definido un SPOTIFY_ARTIST_ID” | Missing artist ID configuration | Set SPOTIFY_ARTIST_ID environment variable |
Method returns null | API request failed | Check logs for specific error details |
Dependencies
@/lib/BaseFetcher- HTTP request wrapper@/server/constants- Environment variable configuration@/server/services/cache- Token and response caching@/types/spotify/token.d- Type definitions for token response@/types/spotify/topTracks.d- Type definitions for tracks response