menu

Questions & Answers

Cannot delete tracks from a Spotify playlist using the Spotify API. Receiving 401 error

I've been trying and failing to delete tracks from a playlist using the API. Every method I attempt results in a 401 error from spotify. 

This is a JavaScript Web App and I'm performing both Oauth and delete requests from a Node.js backend. 

I have a valid Oauth2 flow and can create/add tracks to playlists on an authorized account. 

I am using the passport.js Spotify Strategy to secure an access token and I have defined scopes of  'user-read-email',  'user-read-private', 'playlist-modify-public',  'playlist-modify-private',

Here is the code for my route handler in Node/express:

app.get('/api/playlist/update', requireLogin, async (req, res) => {
// * ----- CONFIG ----- (Spotify access token)
const config = {
  headers: {
    Accept: 'application/json',
    Authorization: `Bearer ${req.user.accessToken}`,
    'Content-Type': 'application/json',
  },
};

// * ----- GET SNAPSHOT ID OF PLAYLIST -----
const url = `https://api.spotify.com/v1/playlists/${keys.URI_TOP10}`;

const response = await axios.get(url, config);
const snapshot_id = response.data.snapshot_id;

// console.log(snapshot_id);

// * get tracks
const responseTracks = await axios.get(
  `https://api.spotify.com/v1/playlists/${keys.URI_TOP10}/tracks`,
  config
);
const tracks = responseTracks.data.items;
const trackURIs = tracks.map((track) => {
  return { uri: track.track.uri };
});

// console.log(trackURIs);

// * ----- FORMATE FETCH REQ BODY -----
const body = JSON.stringify({
  snapshot_id: snapshot_id,
  tracks: trackURIs,
});

// console.log(body);

// * ----- DELETE PLAYLIST TRACKS -----
fetch(`https://api.spotify.com/v1/playlists/${keys.URI_TOP10}/tracks`, {
  method: 'DELETE',
  headers: config,
  body: body,
})
  .then((response) => {
    if (response.ok) {
      console.log(
        `Tracks successfully deleted from playlist with ID ${keys.URI_TOP10}`
      );
    } else {
      console.log(response);
      throw new Error('Error deleting tracks from playlist');
    }
  })
  .catch((error) => {
    console.log(error);
  });
Comments:
2023-01-23 23:10:18
Maybe headers: config.headers instead of headers: config? Why are you not using axios like other requests?
Answers(0) :