Skip to content

SanjayPhilip/SoundMind

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🎵 SoundMind: Spotify AI Chatbot - Complete Implementation Guide

Project Overview

SoundMind is a full-stack web application that combines Spotify's music ecosystem with Claude AI to create an intelligent music companion. Users can chat with AI, get personalized recommendations, manage playlists, and discover new music all in one place.


Architecture

┌─────────────────┐
│   React App     │
│  (Port 3000)    │
└────────┬────────┘
         │ HTTP/REST
         ▼
┌─────────────────┐
│  Express.js     │
│  (Port 5000)    │
└─────┬───────────┘
      │
      ├─► Spotify Web API
      │   └─ Auth, Search, Playlists
      │
      └─► Claude API
          └─ Chat, Recommendations

File Structure & Contents

📁 Files You've Received

soundmind/
├── server.js                    # Backend API server
├── spotifyai-frontend.jsx       # React frontend component
├── package.json                 # Node.js dependencies
├── .env.example                 # Environment variables template
├── SETUP_GUIDE.md              # Detailed setup instructions
├── QUICK_START.md              # 10-minute quick start
└── README.md                    # This file

🔧 What Each File Does

server.js (Backend)

  • Handles Spotify OAuth authentication
  • Manages user sessions
  • Integrates with Claude API for chat
  • Searches Spotify for songs
  • Creates and manages playlists
  • Provides RESTful API endpoints

spotifyai-frontend.jsx (Frontend)

  • React component with chat interface
  • Sidebar navigation
  • Message display with AI responses
  • Recommendations grid
  • Spotify login integration
  • Real-time message updates

package.json

  • Defines all Node.js dependencies
  • npm scripts for running the app
  • Project metadata

.env.example

  • Template for environment variables
  • Copy to .env and fill in credentials
  • Never commit .env to version control

Key Features Implemented

1. Spotify Authentication

  • OAuth 2.0 flow
  • Session management
  • User profile retrieval
  • Secure token handling

2. AI Chat Interface

  • Real-time messaging
  • Claude integration
  • Music-aware responses
  • Recommendation extraction

3. Music Discovery

  • Mood-based recommendations
  • Genre suggestions
  • Artist discovery
  • Song search

4. Playlist Management

  • Create playlists
  • AI-suggested tracks
  • Playlist descriptions
  • Track organization

5. User Experience

  • Clean, modern UI
  • Dark/light mode ready
  • Responsive design
  • Real-time feedback

Getting Started (3 Steps)

Step 1: Get Credentials

Step 2: Setup Environment

mkdir soundmind && cd soundmind
cp [downloaded files here]
mv .env.example .env
# Edit .env with your credentials
npm install

Step 3: Run

npm run dev        # Backend on port 5000
# In another terminal
npm start          # Frontend on port 3000

API Endpoints

Authentication

GET  /api/spotify/login          → Redirect to Spotify auth
POST /api/spotify/callback       → Handle auth callback
GET  /api/spotify/user           → Get current user
POST /api/spotify/logout         → Logout user

Chat & AI

POST /api/chat                   → Send message to AI
    Request: { messages: [], spotifyUser: {} }
    Response: { message: "...", recommendations: [] }

POST /api/recommendations/mood   → Get mood-based recommendations
    Request: { mood: "relaxed" }
    Response: { mood: "...", recommendations: [] }

Playlists

POST /api/playlists/create       → Create new playlist
    Request: { playlistName: "...", description: "...", songIds: [] }
    Response: { success: true, playlistId: "...", songCount: 0 }

How It Works

User Flow

  1. Login

    • User clicks "Login with Spotify"
    • Redirected to Spotify authorization
    • Granted scopes and redirected back
    • Session established with tokens
  2. Chat

    • User sends message (e.g., "Indie rock recommendations")
    • Message sent to backend
    • Backend forwards to Claude API
    • Claude responds with music suggestions
    • Backend searches Spotify for suggested tracks
    • Recommendations displayed to user
  3. Create Playlist

    • User requests playlist creation
    • AI suggests songs via Claude
    • Backend creates playlist on Spotify
    • Tracks added to playlist
    • Success confirmation shown

Data Flow

User Input
    ↓
React Component
    ↓
Express Backend
    ├─ Check Authentication
    ├─ Call Claude API
    ├─ Process Response
    ├─ Search Spotify
    └─ Format Results
    ↓
React Component
    ↓
Display to User

Configuration Guide

Environment Variables

# Spotify
SPOTIFY_CLIENT_ID=xxxx          # From Spotify Dashboard
SPOTIFY_CLIENT_SECRET=xxxx      # From Spotify Dashboard
SPOTIFY_REDIRECT_URI=xxxx       # Must match Spotify settings

# Claude
CLAUDE_API_KEY=sk-ant-xxxx      # From Anthropic Console

# Server
PORT=5000                        # Backend port
SESSION_SECRET=xxxx             # Random string (openssl rand -base64 32)

Spotify OAuth Scopes

The app requests these permissions:

user-read-private          # Access user profile
user-read-email            # Access email
user-library-read          # Read saved tracks
user-read-playback-state   # See what's playing
user-modify-playback-state # Control playback
playlist-modify-public     # Create public playlists
playlist-modify-private    # Create private playlists
user-top-read              # See top tracks/artists

Development Workflow

Local Development

# Terminal 1 - Backend
npm install
npm run dev              # Auto-restarts on file changes

# Terminal 2 - Frontend (optional)
cd soundmind-frontend
npm start               # Opens http://localhost:3000

Testing Endpoints

# Check if backend is running
curl http://localhost:5000/api/spotify/user

# Test with minimal data
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [{"role": "user", "content": "Hi"}],
    "spotifyUser": {}
  }'

Debugging

  1. Check Backend Logs

    • Console output from npm run dev
    • Look for errors from Claude/Spotify APIs
  2. Check Frontend Console

    • Browser DevTools (F12)
    • Network tab to see API calls
  3. Environment Variables

    • Verify .env file exists
    • Check all required variables are set
    • Restart server after changing .env

Deployment

Deploy Backend (Heroku Example)

# Install Heroku CLI
npm install -g heroku

# Login to Heroku
heroku login

# Create app
heroku create your-app-name

# Set environment variables
heroku config:set SPOTIFY_CLIENT_ID=xxxx
heroku config:set SPOTIFY_CLIENT_SECRET=xxxx
heroku config:set CLAUDE_API_KEY=xxxx
heroku config:set SESSION_SECRET=xxxx

# Create Procfile
echo "web: node server.js" > Procfile

# Deploy
git push heroku main

# View logs
heroku logs --tail

Deploy Frontend (Vercel Example)

# Install Vercel CLI
npm install -g vercel

# Build React app
npm run build

# Deploy
vercel

# Set environment variable for API URL
vercel env add REACT_APP_API_URL https://your-backend.herokuapp.com

Update Spotify Redirect URI

After deployment, update in Spotify Dashboard:

https://your-frontend.vercel.app

Common Issues & Solutions

Issue Cause Solution
"Cannot find module" Missing npm install Run npm install
Spotify login fails Wrong CLIENT_ID or REDIRECT_URI Verify in .env and Spotify Dashboard
CORS errors Frontend/backend mismatch Check URLs in CORS config
Claude API errors Invalid API key Verify key in Anthropic Console
Port already in use Another process on port 5000 Kill process or use different port
Empty recommendations Song not found on Spotify Check search terms and Spotify availability

Security Checklist

  • .env file added to .gitignore
  • Never commit API keys to Git
  • Use HTTPS in production
  • Validate user input on backend
  • Implement rate limiting
  • Keep dependencies updated
  • Use environment-specific configs
  • Rotate API keys periodically
  • Monitor API usage and costs

Performance Optimization

Backend Optimization

  • Cache Spotify API results
  • Implement request rate limiting
  • Use database for user preferences
  • Compress API responses

Frontend Optimization

  • Lazy load recommendations
  • Implement message pagination
  • Cache album artwork
  • Use React.memo for components

API Optimization

  • Batch Spotify requests
  • Cache Claude responses
  • Implement request debouncing
  • Use CDN for static assets

Future Enhancements

Phase 2 (Medium Priority)

  • Playlist collaboration
  • Voice input/output
  • Music mood analysis
  • Concert recommendations
  • User preferences/settings

Phase 3 (Nice to Have)

  • Real-time notifications
  • Social sharing
  • Analytics dashboard
  • Advanced filtering
  • Mobile app

Dependencies Explained

{
  "express": "^4.18.2",              // Web framework
  "axios": "^1.4.0",                 // HTTP requests
  "dotenv": "^16.3.1",               // Environment variables
  "express-session": "^1.17.3",      // Session management
  "@anthropic-ai/sdk": "^0.8.0",     // Claude API
  "cors": "^2.8.5",                  // Cross-origin requests
  "nodemon": "^3.0.1"                // Auto-restart (dev only)
}

Resources

Official Documentation

Helpful Guides


Support & Troubleshooting

Getting Help

  1. Check Logs - Look at terminal output and browser console
  2. Read Documentation - SETUP_GUIDE.md and QUICK_START.md
  3. Test Endpoints - Use curl or Postman to test API
  4. Verify Credentials - Double-check all environment variables
  5. Check GitHub Issues - Search for common problems

Debugging Tips

# Test Spotify API
curl -H "Authorization: Bearer $TOKEN" https://api.spotify.com/v1/me

# Test Claude API in Node.js
node -e "
const Anthropic = require('@anthropic-ai/sdk');
const client = new Anthropic();
console.log('Claude API connected');
"

# Check Node version
node --version

# See what's using port 5000
lsof -i :5000

Next Steps

  1. Complete Setup - Follow QUICK_START.md
  2. Test Locally - Run backend and test endpoints
  3. Customize UI - Edit colors and styling in React component
  4. Add Features - Extend server.js with new endpoints
  5. Deploy - Host backend and frontend
  6. Monitor - Set up logging and error tracking

License

MIT License - Feel free to use for personal or commercial projects!


Contact & Contribution

Found a bug? Want to contribute?

  • Create an issue on GitHub
  • Submit a pull request
  • Share your improvements!

Happy Coding! 🎵🚀

For questions or issues, refer to:

  • QUICK_START.md (10-minute setup)
  • SETUP_GUIDE.md (detailed guide)
  • API Endpoints section (above)

About

AI-powered music discovery platform

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors