Show your latest Spotify track with a clean OAuth flow and a tiny setup UI.
I wanted a simple way to share the last track I listened to without babysitting tokens. The setup below uses Spotify OAuth once, stores a refresh token, and then keeps the site updated automatically.
What you get:
Everything here uses HTTPS and your real domain. No localhost required.
You can generate the authorize URL manually, but a small setup page keeps it repeatable and easy to share. This is the component I added on /spotify-setup.
These are the only required building blocks:
/spotify-setup page (optional, just to generate the authorize link)/api/spotify/callback API route (required)Go to the Spotify Developer Dashboard, create a new app, and add redirect URIs.
Spotify Dashboard:
https://developer.spotify.com/dashboardRedirect URI to add (use your real domain with HTTPS):
https://your-domain.com/callbackSPOTIFY_CLIENT_ID=your_client_id_here
SPOTIFY_CLIENT_SECRET=your_client_secret_here
SPOTIFY_REDIRECT_URI=https://your-domain.com/callback
SPOTIFY_REFRESH_TOKEN=your_refresh_token_hereVisit /spotify-setup, authorize the app, and copy the refresh token from the /callback page.
This exchanges the authorization code for a refresh token.
// app/api/spotify/callback/route.ts
export async function POST(request: Request) {
const { code } = await request.json();
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
},
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
}),
});
const data = await response.json();
return Response.json({
refreshToken: data.refresh_token,
accessToken: data.access_token,
expiresIn: data.expires_in,
});
}Use your refresh token server-side to refresh access tokens and call the Spotify API:
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
}),
});Top 5 tracks:
That is it. Once the refresh token is in your env vars, the site can display your latest track automatically.
Authorize once, save the token, and your "last listened" line stays live without manual updates.
Opens Spotify, then redirects to `/callback`.
Copy the refresh token into `.env.local`.