Skip to content

About

A fast Blazor WebAssembly Spotify client: library, search, podcasts and in-browser playback.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

SpotifyBlazor logo

SpotifyBlazor

Your Spotify library, player and podcasts in a fast Blazor WebAssembly app, with playback right in the browser.

Live demo

No Spotify account? Click Try the demo on the site: a built-in library of free songs that really play, with the visualizer drawing the actual audio.

Build, test and deploy Terraform .NET 8 Blazor WebAssembly Spotify Web API Azure App Service Application Insights Auth

Screenshots Β· Features Β· Architecture Β· Getting started Β· How it works Β· Troubleshooting


πŸ“Έ Screenshots

Live recording of Now Playing for Ace Frehley's New York Groove with πŸŽ™οΈ Mic on: the Ring around the cover and the bars along the bottom jump in time with the song as the microphone hears it from the speakers
🌈 Winamp style Visualizers β€” eight styles in the album art's colors, mixed and matched, hitting harder in the chorus, or reacting to your mic with πŸŽ™οΈ Mic (recorded live here: the song playing out loud, picked up by a webcam mic, with Ring + Bars reacting)

Wave style: glowing lines flowing across the bottom of Now Playing
Wave
Mirror style: rainbow bars rising from the bottom and hanging from the top
Mirror
Shatter and Particles: the album cover split into tiles flying apart on the beat, with sparks around it
Shatter + Particles

Search results for Daft Punk: top result, songs, and artist cards
Search β€” top result, songs and artists, with filter chips

Album page for Random Access Memories
Album β€” hover a row to play
Now Playing for The Chemical Brothers' Elektrobank, with the synced lyrics panel open and the current line highlighted
Now Playing β€” synced lyrics
Album page for Random Access Memories on a phone, with the top bar hidden and the ☰ Menu in the player bar
Mobile
Artist page for Daft Punk with album grid
Artist β€” albums grid
Liked songs list
Liked β€” songs, albums and podcasts

🎧 Demo mode

Try the demo (on the home page, in the header, or in the ☰ Menu on phones) runs the whole app without a Spotify account. Liked songs, playlists, albums, the artist page, Recently Played, search and the queue all work on a small built-in library. Its songs play in the page with an ordinary audio player, so the 🌈 Visualizer analyzes the real audio, with no mic needed.

How it works: while demo mode is on, DemoSpotifyHandler answers the app's Spotify Web API calls from DemoLibrary in the same JSON shapes Spotify uses, so no page needs a demo branch. Likes and queue changes last until a reload. 🎬 Video is hidden because video search needs a signed-in user.

Demo music by Kevin MacLeod (incompetech.com), licensed under Creative Commons: By Attribution 4.0: Funkorama, Disco Medusae, Club Diver, Local Forecast - Elevator, Volatile Reaction, Ouroboros, Voxel Revolution and Galactic Rap. Each is trimmed to its first 90 seconds with a fade-out. The cover art is original.

✨ Features

🎧 Listen

  • Play in the browser β€” the tab becomes a Spotify Connect device (🌐 This browser)
  • Now Playing with controls, seek, volume and queue
  • Device picker to hand playback between phone, desktop, speakers and browser
  • Synced lyrics on the Now Playing screen (timed lyrics from LRCLIB)
  • Music videos: 🎬 Video finds the song's video on YouTube and plays it in the app
  • 🌈 Winamp style Visualizers in the album art's colors, with eight styles to mix and match under 🎨 Styles (several can be on at once): Bars, a Ring around the pulsing cover, flowing Waves, Particles bursting from the cover, a Tunnel of squares flying outwards, Mirror bars top and bottom, Shatter, which breaks the cover into tiles on the beat, and Warp, a video-feedback swirl where each frame is redrawn zoomed, twisted and hue-shifted so the waveform pours outward in glowing trails. Animated, or with πŸŽ™οΈ Mic reacting to what your microphone hears (Spotify's own audio can't be analyzed in the browser). Repeated lines in the synced lyrics mark the chorus, where it gets bigger and brighter

πŸ“š Browse

  • Liked Songs, saved Albums and Podcasts
  • Album, Artist, Playlist and Podcast pages
  • Search across tracks, artists and albums, with filter chips
  • Recently Played history

πŸ›‘οΈ Reliable

  • OAuth login with automatic, single-flight token refresh
  • Error toasts for failed calls, with a live countdown when rate limited
  • Careful polling that stays inside Spotify's rate limits

πŸ“± Polished

  • Consistent UI built from shared page components
  • Mobile-friendly layout with a compact player bar
  • Application Insights telemetry from client and server

πŸ—οΈ Architecture

A hosted Blazor WebAssembly app: the ASP.NET Core server serves the client and keeps the Spotify client secret and YouTube API key, while the browser talks to Spotify directly for everything else.

flowchart LR
    subgraph Browser
        C["Blazor WASM client<br/>pages Β· player bar Β· toasts"]
        W["Web Playback SDK<br/>(This browser device)"]
        V["YouTube embed<br/>(music video panel)"]
    end

    subgraph Azure["Azure App Service"]
        S["ASP.NET Core server<br/>token exchange Β· JWT Β· telemetry Β· video lookup"]
    end

    SA[("Spotify Accounts")]
    API[("Spotify Web API")]
    YT[("YouTube Data API")]
    AI[("Application Insights")]

    C -- "/api/*" --> S
    S -- "code ⇄ tokens" --> SA
    S -- "/me (mint JWT)" --> API
    S -- "video search (cached)" --> YT
    C -- "library Β· player Β· search" --> API
    C -- "video ids" --> V
    W <--> API
    S --> AI
Loading
Tech Used for
Blazor WebAssembly (.NET 8) The whole UI, hosted by the server
ASP.NET Core Token exchange/refresh, JWT minting, telemetry, rate limiting, music video lookup
Spotify Web API Library, search, player control
YouTube Data API + IFrame Player API Finding a song's music video, and skipping results that won't play outside youtube.com
Spotify Web Playback SDK Playing audio in the browser tab
Application Insights + Serilog Telemetry and logs
πŸ“ Project structure
SpotifyBlazor/
β”œβ”€β”€ Client/                  # Blazor WASM UI
β”‚   β”œβ”€β”€ Pages/               # Routed pages (Liked, Album, Artist, Search, ...)
β”‚   β”œβ”€β”€ Shared/              # PlayerBar, DevicePicker, VolumePopup, Toasts, ...
β”‚   β”œβ”€β”€ Services/            # SpotifyAuthService, WebPlayerService, TelemetryService,
β”‚   β”‚                        # NotificationService, ErrorNotificationHandler
β”‚   └── wwwroot/             # css/app.css, JS interop (webplayer.js, playerbar.js, ...)
β”œβ”€β”€ Server/                  # API: token exchange/refresh, JWT, telemetry
└── Shared/                  # Models

πŸš€ Getting started

1. Create a Spotify app

  1. Open the Spotify Developer Dashboard and create an app.
  2. Add the redirect URI https://127.0.0.1:7151/spotcallback.

Important

Spotify no longer accepts localhost redirect URIs. Use the loopback IP 127.0.0.1.

Note

Since 2026, Development Mode apps need the app owner to have an active Spotify Premium subscription and are limited to 5 authorized users (add them under User Management). See Spotify's February 2026 migration guide for removed endpoints and fields.

2. Configure the server

Put these in Server/appsettings.Development.json or, better, dotnet user-secrets:

Key Purpose
ConnectionStrings:clientId Spotify app client ID
ConnectionStrings:clientSecret Spotify app client secret (server only)
ConnectionStrings:callbackUri Redirect URI β€” must exactly match the one in the dashboard
Jwt:Key / Jwt:Issuer / Jwt:Audience App JWT signing and validation
ApplicationInsights:ConnectionString Telemetry destination
YouTube:ApiKey Optional. YouTube Data API v3 key for the 🎬 Video button (server only; free quota is about 100 searches a day, and results are cached)

Warning

Keep secrets out of source control: use dotnet user-secrets locally and App Service application settings in Azure.

3. Run it

The server project also serves the WebAssembly client:

dotnet run --project SpotifyBlazor/Server

Then open https://127.0.0.1:7151 and log in with Spotify.

πŸ§ͺ Tests

dotnet test tests/SpotifyBlazor.Tests

xUnit tests for the visitor stats (who counts as signed in, page grouping, limits), the "Longer than" filter, and demo mode's stand-in for the Spotify API, plus bUnit tests that render pages and components the way a visitor sees them: the home page signed out and in demo mode, the About page, the header and the length picker. They need no Spotify account or Azure access, and every pull request runs them before anything deploys.

☁️ Deploying

The app is published from Visual Studio to Azure App Service. Set the App Service stack to .NET 8 (LTS) under Configuration β†’ General settings β€” a framework-dependent .NET 8 build won't start on an older runtime.

The live site sits behind a Cloudflare Worker on the custom domain. The free F1 plan allows only 165 MB of outbound data a day, so the Worker caches demo mode's songs and covers at Cloudflare's edge, which means repeat plays don't count against Azure. Only /demo/ is cached: those files never change, while the app's own files aren't fingerprinted and could go stale after a publish.

// In the Worker's fetch handler, where it forwards the request to the App Service:
const isDemoAsset = request.method === "GET" && new URL(request.url).pathname.startsWith("/demo/");
return fetch(upstreamRequest, isDemoAsset
    ? { cf: { cacheEverything: true, cacheTtl: 60 * 60 * 24 * 30 } }  // 30 days at the edge
    : undefined);

πŸ—οΈ Infrastructure as code (Terraform)

infra/ builds the Azure side with Terraform (azurerm): resource group, Linux App Service plan + Web App with a managed identity, Key Vault for the Spotify client secret and JWT key (as Key Vault references, so secret values never land in code or Terraform state), and Application Insights on Log Analytics. Dev runs locally; prod is built from a reusable module, and state is stored remotely in Azure Storage. A GitHub Actions workflow runs fmt, validate, a mocked terraform test, and a read-only plan of prod over OIDC.

cd infra/envs/prod
terraform init -backend-config="storage_account_name=<state account>"
terraform plan -out tfplan

See infra/README.md for bootstrap, secrets, CI setup and how each Terraform concept maps to the code.


πŸ” How it works

πŸ” Authentication
sequenceDiagram
    autonumber
    actor U as User
    participant C as Blazor client
    participant S as Server
    participant SP as Spotify

    U->>SP: Log in (authorization code flow)
    SP-->>C: Redirect to /spotcallback?code=…
    C->>S: POST /api/spotify/exchange (code)
    S->>SP: Code + client secret
    SP-->>S: Access + refresh tokens
    S-->>C: Tokens
    C->>S: POST /api/auth/spotify-login (access token)
    S->>SP: GET /me
    S-->>C: App JWT (for telemetry and other protected endpoints)
Loading
  • The client secret never leaves the server.
  • Tokens are kept in localStorage. Shortly before the access token expires, the client calls POST /api/spotify/refresh and mints a fresh JWT.
  • Only one refresh runs at a time β€” concurrent API calls wait for it and reuse the new token, which keeps them under the token endpoint's rate limits.
  • Tokens and authorization codes are never written to logs or telemetry.
🌐 In-browser playback (Web Playback SDK)

After login the app loads the Spotify Web Playback SDK, turning the tab into a Spotify Connect device named SpotifyBlazor Web Player (shown as 🌐 This browser in the Devices menu).

Requirements

  • Spotify Premium (free accounts get an account_error; the Devices menu shows a message)
  • The streaming scope β€” already requested at login. If you logged in before it was added, log out and back in.
  • HTTPS (or localhost) and a browser with DRM (EME) support β€” Chrome, Edge and Firefox work

How it works

  • wwwroot/webplayer.js loads the SDK on demand and creates the player. Whenever the SDK needs a token it calls back into .NET (WebPlayerService.GetAccessToken), which refreshes first if needed.
  • WebPlayerService starts the player on login, stops it on logout, and tracks the device ID and errors. Play/pause/track changes in the tab refresh the player bar.
  • If you press play and Spotify reports no active device, the call is retried on the browser player β€” with nothing else playing, music just starts in the browser. If another device is active, playback goes there; switch from 🎧 Devices.
  • Browsers block audio until a user gesture, so audio is unlocked on your first click anywhere in the app.
⏱️ Spotify rate limits

Spotify rate-limits per app (Client ID), shared by every user and every environment β€” the live site and local runs all count against the same allowance. When it runs out, Spotify answers 429 Too Many Requests (QUOTA_EXCEEDED), and login is usually the first thing to break.

The app keeps its background traffic small:

What How often
Player bar "now playing" Every 10 s
Now Playing page Every 10 s, only while the page is open
Device list Every 5 s, only while the 🎧 Devices menu is open
Queue Only while the queue panel is open
Playback changes (play/skip, browser player events) Bursts collapse into one refresh, at most every 2 s

πŸ’‘ Tip: if you add polling, give it a CancellationToken and stop it in Dispose β€” otherwise it keeps running after you navigate away.

Wait times: Spotify's CORS headers don't expose Retry-After to browsers, so the client can't see how long to wait on direct Spotify calls. Calls that go through the server (/api/spotify/exchange, /api/spotify/refresh, /api/auth/spotify-login) pass Spotify's 429 and Retry-After through, and the server's own rate limiter also answers 429 with Retry-After. Those show a countdown in the error toast.

πŸ”” Error notifications

ErrorNotificationHandler sits on the client's HttpClient, so every failed call raises a toast without per-call code:

  • The toast shows the source (Spotify or Server), status, endpoint and the error message from the response body (Spotify's error.message or the server's problem detail).
  • πŸŸ₯ 5xx and 429 are red; 🟧 other 4xx are orange. Network failures get a toast too.
  • Repeats of the same error collapse into one toast with a Γ—N count. Toasts close after 8 s; rate-limit toasts stay until the wait is over (max 5 min).
  • /api/telemetry failures are ignored (they're expected before login).

Show your own message with NotificationService.ShowError(...) / ShowWarning(...).

πŸ—‚οΈ Static file caching

The server sends Cache-Control: no-cache for the app's own .css, .js and .html (including index.html), so browsers revalidate on every load β€” a cheap 304 when nothing changed β€” and pick up a new publish immediately. Blazor's _framework files manage their own caching.

index.html links the stylesheets with ?v=2. That was a one-time bump to push phones off an old cached copy; with no-cache in place it doesn't need changing on each publish.


🩺 Troubleshooting

Symptom What to do
"No music playing" when pressing play No Spotify device is active and the web player isn't ready. Open 🎧 Devices and look for This browser or an error message.
Web player error in the Devices menu "Needs Spotify Premium" means a free account. An authentication error usually means your login predates the streaming scope β€” log out and back in.
Plays but no sound Click anywhere on the page once; browsers block audio until you interact.
Everything stops after about an hour Token refresh is failing. Check the server logs for /api/spotify/refresh errors (e.g. rate limiting or a changed client secret).
Login fails with "Spotify rate limit" / 429 QUOTA_EXCEEDED The app's Client ID is out of Spotify API allowance. Close every open tab of the app (live and local share the quota), wait for the countdown or a few minutes, then log in again. See Spotify rate limits.
Login fails with a 5xx from /api/auth/spotify-login The toast and the browser console show what Spotify's /me returned (e.g. 401 expired token, 403 user not on the app's allowlist).
403 Restriction violated when pressing play The active device is stuck with nothing loaded (common right after the desktop app opens). Close and reopen the Spotify app, or pick a song instead of pressing play.
🎬 Video says videos aren't set up YouTube:ApiKey is missing. Add it to appsettings.Development.json locally, or as the YouTube__ApiKey app setting (or youtube-api-key in Key Vault) in Azure, then restart.
🎬 Video shows "Watch on YouTube" instead of playing The video's owner blocks playback on other sites, and so did the next four results. Nothing to fix; the button opens it on youtube.com.
🎬 Video says it couldn't look up the video Usually the YouTube API's daily quota (about 100 searches) is used up; it resets at midnight Pacific. Server logs show the YouTube response.
Phone still shows the old layout after a publish The browser cached the old CSS. Reload once; if it persists, open the site in an Incognito tab or clear the site's cached files.

Built with πŸ’š and Blazor Β· Not affiliated with or endorsed by Spotify

About

A fast Blazor WebAssembly Spotify client: library, search, podcasts and in-browser playback.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages