Connect Spotify with a local PKCE flow and keep credentials in Cloudflare Worker secrets.
The last-listened line on my portfolio reads Spotify on the server. Visitors see a track name and a link, never an access token or a refresh token. The site runs on Cloudflare Workers; the same setup can be verified locally first.
Spotify authorization is no longer a permanent one-time setup. Refresh tokens have a six-month lifetime measured from the original authorization. Refreshing an access token does not extend that lifetime. Renew the connection before it expires, or after Spotify revokes the grant.
The setup helper runs only on the loopback interface of your own computer. It uses PKCE, a random state, an expiring HttpOnly session cookie, and a server-side code exchange. It checks that recently played tracks are accessible before saving anything. The public website does not exchange codes or display tokens.
Open your application in the Spotify Developer Dashboard. Keep the Web API enabled and register this exact redirect URI:
http://127.0.0.1:6002/callbackSpotify allows HTTP for explicit loopback addresses. Use 127.0.0.1, not localhost. The scheme, port, and path must match. If the app is in Development Mode, check its current user-access requirements.
Use the public client ID of your own application:
pnpm spotify:authorize --client-id=YOUR_PUBLIC_CLIENT_IDOpen http://127.0.0.1:6002 in your browser. The helper requests only user-read-recently-played. Sign in with the Spotify account whose latest track you want to share.
After approval, the helper exchanges the authorization code on your computer and checks the recently played endpoint. It writes the grant to the Git-ignored .env.local with restrictive file permissions. It never prints tokens or puts them into the page. No client secret is needed for this PKCE flow.
pnpm devOpen the portfolio at http://127.0.0.1:6001 and check the last-listened line. An empty playback history is valid: the page simply omits the track. Spotify failures also leave the rest of the portfolio usable.
For Cloudflare, store the values generated by the helper as Worker secrets for your production Worker:
SPOTIFY_CLIENT_IDSPOTIFY_AUTH_METHOD with value pkceSPOTIFY_REFRESH_TOKENSPOTIFY_AUTHORIZED_ATUse the Cloudflare dashboard or your authenticated Wrangler CLI. Never commit .env.local, paste a token into a public issue, or copy it into a browser-visible callback. A local success does not update the production Worker automatically. After setting the secrets, deploy and verify the production page.
Run the same helper again before the six-month lifetime ends. Replace the production refresh token and authorization date after local verification. Do not promise an integration that works forever without renewed authorization.
For a PKCE grant, refresh on the server using the client ID and refresh token. Access tokens normally last about an hour; use the returned expires_in with a safety margin rather than requesting a fresh token on every render.
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: clientId,
refresh_token: refreshToken,
}),
cache: "no-store",
signal: AbortSignal.timeout(5000),
});Keep the response on the server. Handle invalid_grant by renewing authorization, not by hammering the endpoint. Log a safe error category and status; never log the response tokens, request body, or Authorization header. The server reuses an unexpired access token and briefly backs off after failed requests. If Spotify returns a replacement refresh token, the Worker uses it in memory and logs a safe renewal warning: update the durable Worker secret before a restart rather than relying on isolate memory.
The visual example below is separate from the portfolio's last-listened integration. A real /me/top/tracks request also requires the user-top-read scope. The default local helper deliberately does not request that additional access.
/callback no longer expose tokens. Use the local helper instead.Run the local setup helper, then store the grant as a Cloudflare secret. Renew authorization before its six-month lifetime ends.
The local helper opens Spotify and validates the callback.
The helper writes `.env.local` without displaying tokens.