0
votes

I'm trying to get a Spotify access token (with just a Client ID and Client Secret) using Node.js and Spotify Web API Node's Client Credential flow. Here is the code I have:

var SpotifyWebApi = require('spotify-web-api-node');

var spotifyApi = new SpotifyWebApi({
  clientId : clientId, // my Client ID
  clientSecret : clientSecret // my Client Secret
});

spotifyApi.clientCredentialsGrant()
  .then(function(data) {
    spotifyApi.setAccessToken(data.body['access_token']);
  }, function(err) {
    console.log('Something went wrong when retrieving an access token', err);
  });

The problem I'm having is I always get the following error:

TypeError: spotifyApi.clientCredentialsGrant is not a function

I can access many other functions from this library with no problem. For instance, I can write:

console.log(`The Client secret is ${spotifyApi.getClientSecret()}`);
console.log(`The Client ID is ${spotifyApi.getClientId()}`);

And I get the expected output in the console:

The Client secret is [my Client Secret]
The Client ID is [my Client ID]

Interestingly, I can see many other available methods by using WebStorm's Code Completion. In fact, I can see 88 total methods (even more than are listed here), but clientCredentialsGrant() is missing from that list as well.

I thought this would be fairly straightforward, but I must be making a simple mistake somewhere. Has anyone used this method successfully? Or has anyone encountered this error before? Is there a better way I should be doing this?

2

2 Answers

0
votes

you have to use this authorization flow on server-side for security reasons. Apparently it's to avoid you from using your secret token on an app which everyone can read the code. Take a look a this: https://github.com/thelinmichael/spotify-web-api-node#authorization

0
votes

Quick fix for the problem would be to wrap it in an if statement checking for both spotifyApi and the clientCredentialsGrant function :

var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi({
  clientId : clientId, // my Client ID
  clientSecret : clientSecret // my Client Secret
});

// insert this line
if (spotifyApi & spotifyApi.clientCredentialsGrant) {
spotifyApi.clientCredentialsGrant()
  .then(function(data) {
    spotifyApi.setAccessToken(data.body['access_token']);
  }, function(err) {
    console.log('Something went wrong when retrieving an access token', err);
  });
}

Might be a hack, but it works for me.