Spotify on my website
How the home page shows what I'm listening to right now, kept fresh by TanStack Query, with an equalizer that only pretends to hear the music, and how the Stats page shows my top artists, top tracks and the last few songs I played.
If I'm listening to something, the bottom of the home page says so: the song, the artist, the album cover and a little equalizer. When I'm not, the section isn't there at all. And the Stats page has a Spotify section with my top five artists and tracks over the last four weeks, six months and year, plus the last few songs I played.
Both come from Spotify's Web API. Unlike Flighty, there's a proper API this time, so there's no script on my Mac and nothing to push. The site asks Spotify directly.
One token, kept forever
Everything here is about one account, mine, so there's no "Log in with Spotify" button for visitors. What the site needs is a refresh token: a long-lived token that I get once, by logging in myself, and that the server can swap for a short-lived access token whenever it needs one.
Getting it means going through Spotify's login once. Rather than do that by hand with curl, there's a route on the site that does it, and only in development:
export const Route = createFileRoute("/api/spotify/callback")({ server: { handlers: { GET: async ({ request }) => { if (!import.meta.env.DEV) { return new Response("Not found", { status: 404 }) } // … }, }, },})Opening it locally does all three steps:
- With no
codein the URL, it sends me to Spotify's login, asking for three scopes:user-read-currently-playing,user-top-readanduser-read-recently-played. - Spotify sends me back to the same URL with a
code, which the route swaps for a refresh token. - It writes the token to
.env.local, sets it inprocess.envso it works without a restart, and shows it on the page so I can paste it into Vercel's environment variables.
The redirect URI registered in the Spotify dashboard is the route's own URL, and the route builds it from the request, so the two always match.
In production the route is a 404. The refresh token is the only thing that lets anyone read my listening history, so the page that shows it shouldn't exist anywhere but my laptop.
Access tokens, reused
Spotify's access tokens last an hour. Asking for a new one on every request would double the number of calls, so the server keeps the last one while the instance stays warm:
// Reused while the server instance stays warm, so most requests skip the token refreshlet cachedToken: CachedToken | null = null
async function getAccessToken() { if (cachedToken && cachedToken.expiresAt > Date.now()) { return cachedToken.value } // …swap the refresh token for an access token…
// Refresh a minute early so a token never expires mid-request cachedToken = { value: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1000, } return cachedToken.value}Vercel's Fluid Compute reuses function instances between requests, so a module-level variable like this one lasts a lot longer than you'd expect from "serverless".
If any of the SPOTIFY_* variables are missing, it logs a warning and returns null, and both sections simply don't show. A missing Spotify token shouldn't break the home page.
Now playing
The server side is one server function that asks Spotify what's playing:
export const getNowPlaying = createServerFn({ method: "GET" }).handler( async (): Promise<NowPlaying | null> => { // Let Vercel's CDN share one answer between visitors for a few seconds setResponseHeader( "Cache-Control", "public, s-maxage=15, stale-while-revalidate=15" )
const token = await getAccessToken() if (!token) return null
const response = await fetch( "https://api.spotify.com/v1/me/player/currently-playing", { headers: { Authorization: `Bearer ${token}` } } ) // 204 means nothing is playing if (response.status !== 200) return null // … })Two things in there took a while to learn:
- Nothing playing isn't an error. Spotify answers
204 No Content, with no body at all, so the response is checked before it's parsed. A paused track comes back as a200withis_playing: false, which counts as nothing playing too. - Visitors share the answer. With
s-maxage=15, Vercel's CDN answers everyone from the same response for 15 seconds. Ten people on the home page make one call to Spotify, not ten.
The album cover comes in a few sizes, largest first. The card shows it at 44px, so it picks the smallest one that's still sharp on a retina screen:
// Spotify lists covers largest first; take the smallest that's still sharp at 44pxconst albumArt = images.filter((image) => image.width >= 88).at(-1) ?? images[0]After the page has loaded
The page doesn't wait for Spotify. The home page is rendered without the card, and the card fetches once the page has loaded, then checks again every 30 seconds. When a song ends and nothing follows, the section goes away.
Polling with TanStack Query
The first version did that by hand, with a useEffect:
const [track, setTrack] = useState<Track | null>(null)
useEffect(() => { let cancelled = false const update = () => getNowPlaying() .then((next) => !cancelled && setTrack(next)) .catch(() => !cancelled && setTrack(null))
update() const interval = setInterval(() => { if (document.visibilityState === "visible") update() }, POLL_INTERVAL) return () => { cancelled = true clearInterval(interval) }}, [])It worked, but most of it isn't about Spotify. It's a timer, a check that the tab is visible, and a cancelled flag so an answer that arrives after the card has gone doesn't update it. That's the code everyone writes for polling, and gets slightly wrong in a slightly different way each time.
Now it's TanStack Query:
const { data: track } = useQuery({ queryKey: ["spotify", "now-playing"], queryFn: () => getNowPlaying(), refetchInterval: POLL_INTERVAL,})
if (!track) return nullQuery is a cache for data that lives somewhere else, here Spotify, by way of my server. You tell it where the data comes from and how fresh it should be, and it decides when to fetch. What I get without writing any of it:
- Polling stops in a background tab.
refetchIntervalpauses while the tab is hidden. If I ever wanted it to carry on, that'srefetchIntervalInBackground: true. - Coming back catches up straight away. Switch back to the tab and it refetches then, instead of waiting up to 30 seconds for the next tick.
- Nothing lands on a card that's gone. Leave the page and Query stops listening for the answer. No
cancelledflag. - A blip doesn't hide the card. If the request fails, say on a train with no signal, Query tries again three times, waiting longer each time, and keeps showing the last track meanwhile. The old version hid the card on the first failure.
- One request, however many cards. Anything else that asks for
["spotify", "now-playing"]gets the same data from the same request. There's only one card today, but a second one wouldn't double the calls.
queryFn is the server function itself, so the types come for free. getNowPlaying returns NowPlaying | null on the server, and track is that type in the component, without saying so anywhere. Change the shape on the server and the card stops compiling.
It is one more dependency for one component, which is the case against it. But polling is the kind of thing that's easy to write and hard to get right, and the next piece of live data on the site gets all of this for a few lines.
Setting it up
Query needs a QueryClient, provided at the top of the app. The router has a Wrap option for exactly that, a component it renders around everything, so the provider goes where the router's made:
export function getRouter() { // One per router, so the server never shares cached data between requests const queryClient = new QueryClient()
return createTanStackRouter({ routeTree, // … Wrap: ({ children }) => ( <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> ), })}The client is made inside getRouter(), not once at the top of the file. On the server a new router is made for every request, so each request gets its own empty cache. A single client shared by the whole server would hand one visitor's data to the next.
Storybook does the same for each story, so the "nothing playing" story doesn't show the song cached by the "playing" one:
export function AppProviders({ children }: { children: ReactNode }) { // One per story, so a story's mocked data never shows up in the next one const [queryClient] = useState(() => new QueryClient()) return ( <QueryClientProvider client={queryClient}> {/* …the app's other providers… */} </QueryClientProvider> )}Query is one of several TanStack libraries on this site now. How they fit together is in the colophon.
An equalizer that can't hear anything
The card has four bars that bounce like an equalizer. Spotify doesn't share the audio, of course, so there's nothing to listen to. The bars follow random noise instead.
They're the bar visualizer from audiocn, which is normally fed by a microphone or an audio element. It also takes levels painted by hand, so every 140ms the card paints four random ones:
useEffect(() => { if (reducedMotion) return const interval = setInterval(() => { actionsRef.current?.paint( Array.from({ length: BAR_COUNT }, () => 0.25 + Math.random() * 0.75) ) }, NOISE_INTERVAL) return () => clearInterval(interval)}, [reducedMotion])Random numbers alone would twitch. What makes them look like music is the visualizer's smoothing: a bar jumps up straight away and falls back slowly, the way a real equalizer does. It also stops painting while it's off screen.
With less motion turned on, the bars stand still, at heights that still read as an equalizer:
// Shown with reduced motion: still reads as an equalizer, but doesn't moveconst RESTING_LEVELS = [0.55, 1, 0.75, 0.45]The bars are aria-hidden. A screen reader gets the song and the artist, which is the part that's true.
Top artists, top tracks, recently played
On Stats, the Spotify section has three lists side by side: top artists, top tracks and recently played, with a toggle for the period.
Spotify works out the top lists itself, over three periods it calls short_term, medium_term and long_term. They're roughly the last four weeks, six months and year, so that's what the toggle says:
const rangeLabels: Record<SpotifyRange, string> = { short_term: "4 weeks", medium_term: "6 months", long_term: "1 year",}The toggle doesn't fetch anything. All three periods are loaded at once, with the page, so switching is instant and the server and browser always show the same lists. That's seven requests to Spotify, all in parallel:
const [[short, medium, long], recent] = await Promise.all([ // Top artists and top tracks, for each period Promise.all(SPOTIFY_RANGES.map((range) => getTop(token, range))), // Older tokens lack this scope; the top lists still show without it getRecent(token).catch(() => null),])Seven requests sounds like a lot, but the whole Stats page is cached by the CDN for an hour, so Spotify hears from it about once an hour, not once a visit.
Older tokens, newer scopes
Recently played came later than the top lists, and it needs a scope my first refresh token didn't have. A token can't gain scopes. You have to log in again to get a new one.
So recently played is allowed to fail on its own. If it does, it's null, and the section shows the two top lists without it, instead of no Spotify at all. Adding a feature shouldn't take down the ones that already worked.
Songs on repeat
When I like a song, I play it a few times in a row. Spotify's history lists every play, so the last five could easily be the same song five times. The list asks for twenty and skips a track when it's the same as the one before:
// A track on repeat shows oncereturn items .filter( (item, index) => item.track.external_urls.spotify !== items[index - 1]?.track.external_urls.spotify ) .slice(0, RECENT_LIMIT)It only compares neighbours, so a song I played this morning and again tonight still shows twice. That's two separate times I chose it, so it should.
When I played it
Each song in recently played has a number badge, like the top lists. Hovering over it shows when I played it, and a screen reader hears the time as part of the row:
<Tooltip> <TooltipTrigger render={<Badge className="cursor-help" />}> {rank} </TooltipTrigger> <TooltipContent> <time dateTime={at}>{time}</time> </TooltipContent></Tooltip>{/* The tooltip only shows on hover, so the time is read out here too */}<span className="sr-only">Played {time}</span>The time is always shown in London time, whoever's reading:
// Fixed zone so the server and the browser print the same timeconst playedAt = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: "Europe/London",})The page is rendered on the server, in UTC, and then again in your browser, in your time zone. Without a fixed zone, the two would print different times for the same play, and React would complain about the mismatch. And it's my listening history, so my time zone is the one that makes sense anyway.
What I learnt
- A dev-only route beats a how-to. Getting the refresh token is a page I open, not a list of
curlcommands I have to remember next time. - Empty isn't an error. A
204from Spotify is the normal answer for "nothing playing", and the card's answer to it is to not be there. - Let the CDN do the sharing. Fifteen seconds of caching on now playing and an hour on Stats keep the calls to Spotify down to a handful, however many people visit.
- Don't write the polling yourself. Query's version pauses in the background, catches up on focus, retries and cleans up, in five lines instead of twenty.
- Make the cache per request. On the server, a
QueryClientshared by everyone is a data leak. - New features fail on their own. Recently played can break without taking the top lists with it.
- Fake is fine when it's honest. The equalizer doesn't hear the music, but it's hidden from screen readers, and it stands still when you've asked for less motion.