Spotify Web API returning 'Insufficient client scope.' despite full client scopes

48 views Asked by At

I have written a program that intends to add songs to my own spotify playlist.

The below is the auth code:

const { SpotifyWebApi } = require('spotify-web-api-node');

module.exports = async (req, res) => {
  const spotifyApi = new SpotifyWebApi({
    clientId: process.env.SPOTIFY_CLIENT_ID,
    clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
    redirectUri: `${process.env.VERCEL_URL}/api/callback`,
  });

  const scopes = ['playlist-read-private', 'playlist-read-collaborative', 'playlist-modify-public', 'playlist-modify-private', 'user-read-playback-state', 'user-modify-playback-state', 'user-read-currently-playing', 'playlist-read-collaborative', 'user-read-playback-position', 'user-library-modify'];
  const authorizeURL = spotifyApi.createAuthorizeURL(scopes, null);
  res.writeHead(302, { Location: authorizeURL });
  res.end();
};

While you'd think I'd only need playlist-modify-public and private, I included them all after testing to make sure. The /callback function returns the refresh token which I include in my code.

Yet, when I try await spotifyApi.addTracksToPlaylist(playlistId, [`spotify:track:${songId}`]);, I get the following error: "An error occurred while communicating with Spotify's Web API.\nDetails: Insufficient client scope."

I don't see how I can have the incorrect client scope?? I've made sure the tokens are correct. I don't know what to do.

1

There are 1 answers

0
Bench Vue On

The spotify-web-api-node not fully support Authorization Code Flow.

It means you need to provide a call back endpoint as a local server by express.

And request code and exchange into access token.

enter image description here

This tutorial code is best example from spotify-web-api-node

https://github.com/thelinmichael/spotify-web-api-node/blob/master/examples/tutorial/00-get-access-token.js

Demo code

For adding song into your playlist

Save as demo.js

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

const PORT = 3000;  // it need to match your REDIRECT URI's port
const CLIENT_ID = '<your client id>'
const CLIENT_SECRET = '<your client secret>'
const PLAYLIST_ID = '<your playlist id>'
const scopes = [
    'playlist-modify-public',
    'playlist-modify-private'
];

const spotifyApi = new SpotifyWebApi({
    redirectUri: `http://localhost:${PORT}/callback`,
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET
});

const app = express();

app.get('/login', (req, res) => {
    res.redirect(spotifyApi.createAuthorizeURL(scopes));
});

app.get('/callback', (req, res) => {
    const error = req.query.error;
    const code = req.query.code;
    const state = req.query.state;

    if (error) {
        console.error('Callback Error:', error);
        res.send(`Callback Error: ${error}`);
        return;
    }

    spotifyApi
        .authorizationCodeGrant(code)
        .then(data => {
            const access_token = data.body['access_token'];
            const refresh_token = data.body['refresh_token'];
            const expires_in = data.body['expires_in'];

            spotifyApi.setAccessToken(access_token);
            spotifyApi.setRefreshToken(refresh_token);

            spotifyApi.addTracksToPlaylist(PLAYLIST_ID, [
                'spotify:track:4iV5W9uYEdYUVa79Axb7Rh'  // Prelude for Piano No. 11 in F-Sharp Minor
            ])
            res.send('Success! You added a song into your playlist');

            setInterval(async () => {
                const data = await spotifyApi.refreshAccessToken();
                const access_token = data.body['access_token'];
                spotifyApi.setAccessToken(access_token);
            }, expires_in / 2 * 1000);
        })
        .catch(error => {
            console.error('Error getting Tokens:', error);
            res.send(`Error getting Tokens: ${error}`);
        });
});

app.listen(PORT, () =>
    console.log(
        `HTTP Server up. Now go to http://localhost:${PORT}/login in your browser.`
    )
);

How to get your configuration

https://developer.spotify.com/dashboard

enter image description here

Install dependencies

npm install express spotify-web-api-node

Run it

node demo.js

Login by Browser

http://localhost:3000/login

Again the port number needs to match your configuration.

result

enter image description here

enter image description here

Similar implementation by Next.js

get Spotify Oauth in NextJS but doesn't work