When we listen to music at home, my son always asks to add/remove the currently playing track to/from his Spotify playlist of favorites. I decided to automate this process and it started with this simple little service that runs as a small public API. It runs on a Cloudflare Workers using Hono. At home, I use HomeAssitant to send those calls from a small remote control, and have a lamp and a speaker give confirmation when the track is added/removed.
-
Install dependencies:
pnpm install
-
Configure Spotify credentials:
- Create a Spotify app at https://developer.spotify.com/dashboard
- Get
SPOTIFY_CLIENT_IDandSPOTIFY_CLIENT_SECRET - Get your target playlist ID from Spotify. You can use the Spotify Web app and get it from the URL, or use the /playlists endpoint of this service.
-
Set local environment variables in
.dev.vars:BEARER_TOKEN=your_bearer_token_here SPOTIFY_CLIENT_ID=your_spotify_client_id SPOTIFY_CLIENT_SECRET=your_spotify_client_secret -
Update wrangler.jsonc with your playlist ID and configure production settings as needed.
-
Visit https://yourappdomain.com/api/auth/login (with your Authorization Bearer Token) to initate the OAuth flow from Spotify and get your credentials.
pnpm run devServer runs on http://localhost:8787
Public:
GET /- Landing pageGET /health- Health check, returns{ status: "ok", timestamp }
Protected (require Authorization: Bearer <token> header):
GET /current- Get currently playing trackGET /playlists- Get all your playlists, useful to get the playlist IDPOST /add- Add currently playing track to playlistPOST /remove- Remove currently playing track from playlistPOST /play- Play the playlistGET /auth/login- Initiate the OAuth flow from Spotify
Rate limiting: 60 requests/minute per token (429 if exceeded)
-
Set production secrets:
pnpx wrangler secret put BEARER_TOKEN pnpx wrangler secret put SPOTIFY_CLIENT_ID pnpx wrangler secret put SPOTIFY_CLIENT_SECRET
-
Deploy:
pnpm run deploy
400- No track currently playing or validation error401- Missing/invalid Bearer token404- Playlist not found409- Track already in playlist (add endpoint)429- Rate limit exceeded502- Spotify API error