I’m building a React app using Spotify Web Playback sdk. I was following this guide here, but I’m struggling to refresh the token using Authorization Code flow.
I know Spotify uses refresh_token to get a fresh token (expiration is 1h), but I’m not getting how it works in practice.
This is my auth callback:
router.get("/auth/callback", (req, res) => {
console.log("spotify callback");
var code = req.query.code;
var authOptions = {
url: "https://accounts.spotify.com/api/token",
form: {
code: code,
redirect_uri: "http://localhost:3001/spotify/auth/callback",
grant_type: "authorization_code",
},
headers: {
Authorization:
"Basic " +
Buffer.from(
process.env.SPOTIFY_CLIENT_ID +
":" +
process.env.SPOTIFY_CLIENT_SECRET
).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
},
json: true,
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log("auth ok", body);
access_token = body.access_token;
refresh_token = body.refresh_token;
res.redirect("http://localhost:8080");
} else {
console.log("ERROR AUTH", error, response);
}
});
});
I’m returning both tokens to the UI app with this:
router.get("/auth/token", (req, res) => {
res.json({
access_token: access_token,
refresh_token: refresh_token,
});
});
So far the UI part is basically a react component that calls /auth/token
api and, if token is present, it renders the player. Everything works good except that after 60 minutes I would need to reauthenticate.
How can I ask a fresh token? Do I need to calculate the expiration in UI side and, if >1h, request a new token?
Ensure that the Spotify account being used for playback is a Premium account, as the Web Playback SDK requires it.
or
Check Token Expiry
or
Check Your Access Token
sayed ehab is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.