Scrawl

Shipping A Full Spotify Real-Time Status App

· 7 min read

I wanted a tiny page that answers one question, live: what am I listening to right now?

Built entirely with Next.js (App Router), this application provides a sleek, real-time look into your current Spotify playback state. Instead of reaching out to Spotify directly from the browser (and leaking your API secrets), we funnel everything through a secure, server-rendered Next.js backend.

What Spotify changed in 2026

The February Web API changelog still lists the three playback reads this kind of app needs. The portfolio widget reads the account’s current track using the first endpoint.

These Web API calls return snapshots. I didn't find a documented account-wide stream of playback events for a status widget. The Web Playback SDK’s player_state_changed event describes the SDK player running in the browser. For a status widget that follows the account across devices, the implementation below still polls. If you add a history fallback, label it “Last played” and keep its timestamp separate from live progress. The history endpoint covers tracks and excludes podcast episodes. This walkthrough also skips episodes in the current item.

The bigger changes are in access and authorization.

  • Development Mode. The app owner needs active Premium, and new apps are limited to five authorized users. In this build, the owner authorizes the Spotify account and visitors read the widget’s server response. Only the owner connects an account. Spotify postponed the endpoint access changes for existing integrations on March 9. If you extend this build beyond playback, check the migration guide for the library, catalog, and playlist changes that apply to your app.
  • Refresh tokens expire. Spotify introduced a six-month lifetime on June 18 for new apps and July 20 for existing apps. The clock starts when the user authorizes the app. Exchanging the refresh token for an access token does not extend it. On 400 invalid_grant, run authorization again and replace the refresh token in your deployment. Access tokens still last about an hour. Spotify’s token refresh guide

Here is the file layout for the standalone polling demo below. The portfolio homepage uses its own server-rendered widget.

Project files
app/api/now-playing/route.ts
Polling endpoint
app/lib/spotify.ts
Server-only Spotify API wrapper
app/page.tsx
Page that renders the widget
components/ui/now-playing.tsx
Playback status component
.env.local
Local Spotify credentials
next.config.ts
Next.js configuration

That sounds simple, but doing it properly means solving token refresh, null states, no-cache data, and safe server boundaries. This scrawl is the build log of that journey, written so you can ship your own version without the usual OAuth pain.

What This App Actually Does

By the end of this build, we have:

  • A strict server-only Spotify data layer.
  • A resilient /api/now-playing endpoint.
  • A frontend that polls cleanly and never explodes on paused playback.
  • A live embeddable experience you can drop into your portfolio.

Environment Variables

Use this .env.local baseline:

env
SPOTIFY_CLIENT_ID=
SPOTIFY_CLIENT_SECRET=
SPOTIFY_REFRESH_TOKEN=
NEXT_PUBLIC_NAME=Harshit

Optional fallback for temporary debugging:

env
SPOTIFY_ACCESS_TOKEN=

Core Spotify Module (Exact Pattern)

This is the server-only module for the standalone demo:

ts
import "server-only";
const SPOTIFY_CURRENTLY_PLAYING_ENDPOINT =
"https://api.spotify.com/v1/me/player/currently-playing";
export type CurrentPlayback = {
isPlaying: boolean;
progressMs: number;
timestampMs: number;
durationMs: number;
trackId: string;
trackName: string;
artists: string[];
albumName: string;
albumImageUrl: string | null;
spotifyUrl: string | null;

Real-Time API Route

This is the route contract the client consumes. Notice how it keeps the response shape stable even when Spotify fails.

ts
import { NextResponse } from "next/server";
import { getCurrentPlayingSong } from "@/app/lib/spotify";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const song = await getCurrentPlayingSong();
return NextResponse.json({ song });
} catch {
return NextResponse.json({ song: null }, { status: 500 });
}
}

Why This Endpoint Is Reliable

  • force-dynamic + no-store keeps data fresh for every request.
  • 204 maps to null cleanly, not an app crash.
  • Stable { song } output keeps client logic dead simple.
  • Spotify outages degrade gracefully to song: null.

Client Polling Pattern

ts
const pollNowPlaying = async () => {
const res = await fetch("/api/now-playing", { cache: "no-store" });
if (!res.ok) return;
const data = await res.json();
setSong(data.song);
};
pollNowPlaying();
const int = setInterval(pollNowPlaying, 5000);
return () => clearInterval(int);

How To Get A Spotify Refresh Token (Without Guesswork)

For a personal widget, use the refresh token script from the portfolio repository. Add http://127.0.0.1:8888/callback to your Spotify app’s redirect URIs and put SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in your ignored .env.local. From the repository root, run:

bash
node --env-file=.env.local scripts/spotify-refresh-token.mjs

Open the printed authorization URL. The script checks the callback state and exchanges the authorization code on your machine. Copy the SPOTIFY_REFRESH_TOKEN line from your terminal into your local or deployment secrets. Run it again when you need to reauthorize. The default scope covers the current track. To enable history too, append user-read-currently-playing user-read-recently-played to the command.

The steps below show the same flow manually.

1) Create Spotify App

  1. Go to Spotify Developer Dashboard.
  2. Create an app. For Development Mode, use the Premium account that will own it.
  3. Copy Client ID and Client Secret.
  4. Register the exact callback URI your local listener serves, such as http://127.0.0.1:3000/callback for the manual example. Spotify accepts HTTP for literal loopback addresses. Use HTTPS for deployed callbacks. Redirect URI rules

2) Scopes You Need

Request user-read-currently-playing for this walkthrough. Add the other scopes listed above only if you call those endpoints.

3) Build Authorization URL

Replace placeholders and open this in the browser:

txt
https://accounts.spotify.com/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A3000%2Fcallback&scope=user-read-currently-playing&state=YOUR_RANDOM_STATE

Generate a fresh random state before opening the URL. After approval, Spotify redirects to your callback with the code and state. Confirm the returned state matches, then exchange the code. Authorization Code flow

4) Exchange Code For Refresh Token

Use curl and replace placeholders:

bash
curl -X POST "https://accounts.spotify.com/api/token" \
-H "Authorization: Basic BASE64(CLIENT_ID:CLIENT_SECRET)" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code&code=AUTH_CODE_FROM_CALLBACK&redirect_uri=http://127.0.0.1:3000/callback"

You should receive refresh_token and access_token. Save the refresh token securely.

5) Put Secrets In Env

env
SPOTIFY_CLIENT_ID=...
SPOTIFY_CLIENT_SECRET=...
SPOTIFY_REFRESH_TOKEN=...

The five-second example suits a local walkthrough. On a public page, each open tab can add requests against the same app limit. Reuse the access token until it’s close to expiry, coalesce simultaneous server reads, and pause polling when the page is hidden. A production route should surface upstream 429 and forward Retry-After so the poller can wait before trying again. Use the latest progress_ms to animate progress locally between snapshots while the track is playing. Spotify rate limits

Production Notes That Matter

  • Never expose CLIENT_SECRET or REFRESH_TOKEN on client side.
  • Keep Spotify fetches server-only.
  • Return a stable JSON shape even on failure.
  • Choose a polling interval based on traffic and back off when Spotify rate limits you.
  • Log HTTP status and a safe error code for debugging. If refresh returns invalid_grant, replace the token through a fresh authorization instead of retrying it.

If you only remember one thing from this post: treat Spotify credentials like database credentials, never browser credentials.

Shipping Checklist

  • Spotify app created with correct redirect URI.
  • Required scopes granted.
  • Refresh token captured and stored in deployment secrets.
  • /api/now-playing returns live payload locally.
  • Polling UI updates progress and handles paused state.
  • Embeds render cleanly across README and website.

Live Spotify status

Open live status

I hope this scrawl saves you hours of frustration and gets your Spotify status live with confidence. Keep authorization on the server and make sure you can reconnect the account when the refresh token expires.