1
votes

I have setup correct my Client Credential flow and i can get my token to make my calls but after 3600 i want to get new (My app use only "public" spotify endpoints) I use https://github.com/thelinmichael/spotify-web-api-node.

Sorry for my english.

const express = require('express');
const router = express.Router();
const SpotifyWebApi = require('spotify-web-api-node');

// Create the api object with the credentials
const spotifyApi = new SpotifyWebApi({
  clientId: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
  clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
});

// Retrieve an access token.
spotifyApi.clientCredentialsGrant().then(
  function(data) {
    console.log('The access token expires in ' + data.body['expires_in']);
    console.log('The access token is ' + data.body['access_token']);
    // Save the access token so that it's used in future calls
    spotifyApi.setAccessToken(data.body['access_token']);
    // console.log('The refresh token is ' + spotifyApi.getRefreshToken());
  },
  function(err) {
    console.log('Something went wrong when retrieving an access token', err);
  }
);

router.get('/getArtistAlbums', function(req, res, next) {
  const user_id = req.query['id'];
  spotifyApi
    .getArtistAlbums(user_id, {
      limit: 10,
      offset: 20
    })
    .then(
      function(data) {
        res.send(data.body);
      },
      function(err) {
        console.error(err);
      }
    );
});
1

1 Answers

0
votes

Instead of refreshing the obtained token (which is not possible when using the clientCredentialsGrant, just request a new token.

//This function will create a new token every time it's called
function newToken(){
    spotifyApi.clientCredentialsGrant().then(
        function(data) {
            ...

            // Save the access token so that it's used in future calls
            spotifyApi.setAccessToken(data.body['access_token']);
        },
        function(err) {
            ... //Error management
        }
    );
}

//When the app starts, you might want to immediately get a new token
newToken();

//And set an interval to "refresh" it (actually creating a new one) every hour or so
tokenRefreshInterval = setInterval(newToken, 1000 * 60 * 60);