DEV Community

Tariq Mehmood
Tariq Mehmood

Posted on

Automate Your Spotify Playlists Using Node.js

If you're tired of hitting "Repeat" on the same songs or spending hours tweaking playlists, this project is for you.

Imagine a Spotify bot that listens with you — detecting your preferences, learning your moods, and generating personalized playlists that evolve as your music taste shifts. Thanks to the power of Node.js and the Spotify Web API, this isn't just possible — it's easier than you might think.

In this article, we’ll build a Smart Spotify Bot that uses real audio features and behavior analysis to automatically generate custom playlists. Whether you want upbeat tracks for workouts or mellow vibes for coding, this bot has you covered.

Tools You’ll Need

  • A Spotify Developer Account
  • A registered Spotify app (Client ID, Client Secret)
  • Node.js & npm
  • REST & OAuth 2.0 basics
  • A code editor like VS Code
  • Your favorite music taste

Project Overview

Here’s what our bot will do:

  • Authenticate the user (OAuth 2.0)
  • Pull top tracks from Spotify
  • Analyze them using Spotify’s audio features (like danceability, tempo, etc.)
  • Apply smart filters to find tracks that match your desired mood
  • Create a playlist and fill it with those tracks
  • Optionally, automate it on a schedule or extend it with genre/mood filters

Step 1: Set Up Spotify App & Environment

1. Create a Spotify App

Go to the Spotify Developer Dashboard
, create an app, and set your Redirect URI (e.g., http://localhost:8888/callback).

2. Initialize Node Project

mkdir smart-spotify-bot && cd smart-spotify-bot
npm init -y
npm install express axios dotenv querystring open
Enter fullscreen mode Exit fullscreen mode

3. Create .env

SPOTIFY_CLIENT_ID=your_client_id
SPOTIFY_CLIENT_SECRET=your_client_secret
SPOTIFY_REDIRECT_URI=http://localhost:8888/callback
Enter fullscreen mode Exit fullscreen mode

Step 2: Build the OAuth Flow with Express

// auth.js
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const querystring = require('querystring');
const open = require('open');

const app = express();
const PORT = 8888;

const SCOPES = [
  'user-read-private',
  'playlist-modify-public',
  'user-top-read'
].join(' ');

app.get('/login', (req, res) => {
  const params = querystring.stringify({
    response_type: 'code',
    client_id: process.env.SPOTIFY_CLIENT_ID,
    scope: SCOPES,
    redirect_uri: process.env.SPOTIFY_REDIRECT_URI,
  });
  res.redirect(`https://accounts.spotify.com/authorize?${params}`);
});

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

  try {
    const tokenRes = await axios.post('https://accounts.spotify.com/api/token',
      querystring.stringify({
        code,
        redirect_uri: process.env.SPOTIFY_REDIRECT_URI,
        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',
        },
      }
    );

    const { access_token, refresh_token } = tokenRes.data;
    console.log('Access Token:', access_token);
    console.log('Refresh Token:', refresh_token);

    res.send('✅ Auth complete. Check your console.');
  } catch (err) {
    console.error('Error:', err.response.data);
    res.send('❌ Failed to authenticate.');
  }
});

app.listen(PORT, () => {
  console.log(`🔐 Go to http://localhost:${PORT}/login`);
  open(`http://localhost:${PORT}/login`);
});
Enter fullscreen mode Exit fullscreen mode

Run it:

node auth.js
Enter fullscreen mode Exit fullscreen mode

Step 3: Fetch and Filter Top Tracks

Get Top Tracks

async function getTopTracks(token) {
  const res = await axios.get('https://api.spotify.com/v1/me/top/tracks?limit=20', {
    headers: { Authorization: `Bearer ${token}` },
  });
  return res.data.items;
}
Enter fullscreen mode Exit fullscreen mode

Get Audio Features

async function getAudioFeatures(token, trackIds) {
  const res = await axios.get(`https://api.spotify.com/v1/audio-features?ids=${trackIds.join(',')}`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  return res.data.audio_features;
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Filter by Mood and Create Playlist

function filterTracksByMood(tracks, features) {
  return tracks.filter((_, i) => {
    const f = features[i];
    return f.energy > 0.65 && f.valence > 0.5 && f.danceability > 0.6;
  });
}

async function createPlaylist(token, userId, name) {
  const res = await axios.post(`https://api.spotify.com/v1/users/${userId}/playlists`, {
    name,
    description: 'Auto-generated by Smart Spotify Bot',
    public: false
  }, {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });
  return res.data.id;
}

async function addTracksToPlaylist(token, playlistId, uris) {
  await axios.post(`https://api.spotify.com/v1/playlists/${playlistId}/tracks`, {
    uris
  }, {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Run the Bot

async function runSmartBot(token) {
  const topTracks = await getTopTracks(token);
  const trackIds = topTracks.map(t => t.id);
  const features = await getAudioFeatures(token, trackIds);

  const filtered = filterTracksByMood(topTracks, features);
  const uris = filtered.map(t => t.uri);

  const me = await axios.get('https://api.spotify.com/v1/me', {
    headers: { Authorization: `Bearer ${token}` }
  });
  const userId = me.data.id;

  const playlistId = await createPlaylist(token, userId, '🎶 Auto Vibes');
  await addTracksToPlaylist(token, playlistId, uris);

  console.log(`✅ Created playlist with ${uris.length} tracks`);
}
Enter fullscreen mode Exit fullscreen mode

Expand the Bot

You’ve got a working APK Spotify Premium playlist generator — but this is just the beginning. Here are some ideas to take it further:

Schedule It

Use node-cron to run the bot weekly or daily.

Genre-Based Filters

Filter by genres like chill, rock, or EDM using track metadata.

Mood Detection by Time/Weather

Use APIs (like OpenWeather) to change playlist themes based on real-time data.

Save Listening Data

Store user track data in a database to analyze trends and evolve the playlist algorithm over time.

Final Thoughts

Spotify’s API is an amazing playground for creative automation. With a few lines of JavaScript and a bit of logic, you can build a personal music assistant that adapts to you — not the other way around.

Start small, build something fun, and before you know it, you’ll have a smart music ecosystem that plays what you love, when you love it.

Ready to build your own music butler? 🎶
Go fork this into your next project and let your code curate your vibe.

Top comments (0)