Let me plan the architecture. I'll build:
Backend: Node.js + Express 5, music-metadata for parsing ID3 tags, multer for uploads, JSON storage (lowdb-style but hand-rolled atomic writes), streaming with Range requests, cover art extraction, scan library folder.
Frontend: React 19 + Vite 8, zustand for state, lucide-react icons, custom CSS (no Tailwind to avoid extra build complexity... though Tailwind v4 would be nice. Let me use plain CSS with a strong design system — more control, no dependency risk). Web Audio API for visualizer.
Features:
- Library scan of local disk folder (music files), extract metadata (title, artist, album, duration, year, genre, cover art)
- Upload files
- Stream with range requests
- Playlists CRUD (JSON)
- Favorites
- Search / filter / sort
- Queue with shuffle, repeat
- Now playing bar + full-screen immersive view
- Audio visualizer
- Keyboard shortcuts
- Responsive design
Let me check if there are any music files available for testing.
Let me plan tasks.
Directory structure:
~/Project/Music
├── package.json (root, workspaces + scripts)
├── README.md
├── .gitignore
├── server/
│ ├── package.json
│ ├── src/
│ │ ├── index.js
│ │ ├── config.js
│ │ ├── db.js
│ │ ├── scanner.js
│ │ ├── metadata.js
│ │ ├── routes/
│ │ │ ├── tracks.js
│ │ │ ├── playlists.js
│ │ │ ├── stream.js
│ │ │ └── library.js
│ │ └── utils/
│ └── data/ (json + music)
└── web/
├── package.json
├── vite.config.js
├── index.html
└── src/
├── main.jsx
├── App.jsx
├── styles/
├── store/
├── components/
└── lib/
Let me start. First create package files and install dependencies in background while I write code.
Actually let me be efficient: write root package.json, server package.json, web package.json, then npm install in background.
Let me think about the design carefully. A "modern" music player. I want something visually striking — dark theme, warm amber/orange accent, glassmorphism, big typography, album art grid. Let me do a refined "editorial" aesthetic rather than generic Spotify clone: deep charcoal/ink background, warm cream text, accent color that adapts to album art dominant color.
Design system:
- Background: #0a0a0b / #111113
- Surface: rgba(255,255,255,0.04)
- Text: #f5f3ef (warm white), muted #8a8783
- Accent: dynamic from album art, fallback #f0a05a (warm amber)
- Font: system UI + a display serif? Let me use "Instrument Serif" or "Fraunces" for headings via Google Fonts... but offline environment might not have internet at runtime for user. I'll include a font stack with fallbacks and try Google Fonts link. Actually better: use local system fonts with a nice stack, plus optional web font. I'll use Google Fonts link (Inter + Instrument Serif) — it degrades gracefully.
Layout:
- Left sidebar (nav, playlists) 260px
- Main content scroll area with top bar (search, view toggles)
- Right panel: Now Playing / Queue (toggleable) 340px
- Bottom player bar full width (except sidebar offset? no, full width)
Pages: Home (recently added, albums), Tracks (list), Albums (grid → detail), Artists, Playlists, Favorites, Search.
Let me keep it well-scoped but complete. I'll implement a client-side router with hash-free history? Simpler: use React Router 7? That's another dep. I'll implement a lightweight view state in zustand (view + params) — avoids router complexity and works well for an app-like SPA. But deep linking is nice. Let me use a minimal custom hash router... Actually let's just use react-router-dom v7, it's standard and reliable. Hmm, but with only a few routes, my own state-based nav is fine and less risk. I'll do a small history-based router with pushState to keep back button working.
Let me just do state-based views with a simple navigate() that pushes to history — clean.
Backend details:
config: MUSIC_DIR env, default server/data/library, DATA_DIR server/data. db.js: JSON file store with atomic write (write tmp + rename), debounced? No — synchronous-ish with queue to avoid corruption. Simple: load once at boot, save() serializes with a write queue.
…:
{
"version": 1,
"tracks": [ { id, filename, title, artist, album, albumArtist, genre, year, track, disk, duration, bitrate, sampleRate, channels, codec, size, mtime, addedAt, coverId, favorite, playCount, lastPlayedAt } ],
"playlists": [ { id, name, description, trackIds, createdAt, updatedAt } ],
"settings": { ... }
}
Cover art: extract embedded picture on scan, save to data/covers/<albumKey>.<ext>, store coverUrl. Dedupe by album hash.
Scanning: walk directory recursively, filter extensions, parse metadata with music-metadata, upsert by relative path. Handle deletions (remove tracks whose file is gone). Progress reporting via SSE? Could be nice: POST /api/library/scan returns after done; frontend shows spinner. Keep simple with a scan status endpoint + polling. I'll do scan with a job state and SSE... maybe overkill. I'll do a synchronous scan endpoint that returns stats, with a scanning flag to prevent concurrent scans. For a few hundred files it's fine.
Upload: multer to temp then move into library dir, parse, upsert. Limit 100MB.
Streaming: /api/tracks/:id/stream with range support, content-type from codec, ETag, 206, 416, HEAD support.
Cover: /api/covers/:name with caching headers.
API:
- GET /api/tracks?search=&sort=&album=&artist=&favorite=
- GET /api/tracks/:id
- PATCH /api/tracks/:id (favorite, playCount)
- DELETE /api/tracks/:id
- POST /api/tracks/upload
- GET /api/tracks/:id/stream
- GET /api/albums, /api/artists
- GET/POST /api/playlists, GET/PATCH/DELETE /api/playlists/:id, POST /api/playlists/:id/tracks, DELETE ...
- POST /api/library/scan, GET /api/library/stats
- GET /api/health
Let me also add "delete track" removes file? Dangerous. I'll make it remove from library and optionally delete file with ?deleteFile=true. Keep default false.
Frontend audio engine: single <audio> element created once, exposed via context. Web Audio analyser for visualizer — requires CORS-clean source; same origin via Vite proxy, so fine.
State (zustand):
- library: tracks, albums, artists, loading
- player: queue, index, isPlaying, currentTime, duration, volume, muted, shuffle, repeat, playTrack(contextTracks, trackId)
- ui: view, nowPlayingOpen, queueOpen, search
Persist volume, favorites server-side, queue maybe localStorage.
Let me write good code. Start with package.json files and install.
I'll use ESM everywhere ("type": "module").
Root package.json with npm workspaces:
{
"name": "rune-music",
...
"workspaces": ["server", "web"],
"scripts": {
"dev": "concurrently -n api,web -c yellow,cyan \"npm:dev:server\" \"npm:dev:web\"",
"dev:server": "npm --workspace server run dev",
"dev:web": "npm --workspace web run dev",
"build": "npm --workspace web run build",
"start": "npm --workspace server run start"
}
}
Add concurrently dev dep at root.
Server deps: express, music-metadata, multer, cors (maybe not needed with proxy but useful), nanoid? Use crypto.randomUUID.
For production, server serves web/dist statically.
Let me write files now. I'll create the plan first.
Note tool call limit per response: 20. Fine.
Let me create the scaffolding.
I need to be careful with Express 5: wildcard route syntax changed (* → /*splat). I'll use app.use fallback or app.get('/{*splat}', ...). Express 5 supports /{*splat}.
Also multer 2.5.0 API same.
music-metadata v12 is ESM-only, parseFile from 'music-metadata'. Good.
Let me write.
First: package.jsons + install in background.
For cover extraction: metadata.common.picture array of {format, data}. Write buffer.
Dominant color: compute on the client from image via canvas. Good — dynamic theming.
Let's create files.
Server code:
config.js:
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export const ROOT = path.resolve(__dirname, '..');
export const DATA_DIR = process.env.DATA_DIR ? path.resolve(process.env.DATA_DIR) : path.join(ROOT, 'data');
export const MUSIC_DIR = process.env.MUSIC_DIR ? path.resolve(process.env.MUSIC_DIR) : path.join(DATA_DIR, 'library');
export const COVERS_DIR = path.join(DATA_DIR, 'covers');
export const DB_FILE = path.join(DATA_DIR, 'db.json');
export const PORT = Number(process.env.PORT || 4000);
export const AUDIO_EXTENSIONS = new Set(['.mp3',...]);
export const MAX_UPLOAD = 200*1024*1024;
db.js:
class Database { data; #queue; ... }
Implement with async write chain and fs.promises.
import fs from 'node:fs/promises';
import path from 'node:path';
import { DB_FILE, DATA_DIR } from './config.js';
const DEFAULT = { version: 1, tracks: [], playlists: [], createdAt: ... };
let state = null;
let writeChain = Promise.resolve();
export async function initDb() { ... mkdir, read or create }
export function db() { return state }
export function save() { const snapshot = JSON.stringify(state,null,2); writeChain = writeChain.then(()=>atomicWrite(DB_FILE, snapshot)).catch(...); return writeChain; }
Need to be careful: writing snapshot each save is fine.
Atomic write: write to ${file}.tmp-${random} then rename.
Add debounce? Saves are infrequent. Fine.
scanner.js:
- walk dir
- for each audio file, parse metadata
- compute id from relative path (stable):
sha1(relPath).slice(0,16)? But renaming creates new id. Use stable hash of relPath; upsert by relPath. Keep existing id if found. - store
file = relative path, mtimeMs, size. - Skip unchanged files (same mtime+size) unless force.
- Cover: hash of album+artist for dedupe; write
covers/<hash>.<ext>; store cover filename. - duration, bitrate, codec, sampleRate, channels, lossless, year, genre[], trackNo, diskNo.
- Also compute
addedAt.
Return {added, updated, removed, skipped, total, durationMs}.
metadata.js: parse with music-metadata, produce normalized object.
cover.js: handle picture write, ext from format ('image/jpeg' → .jpg).
Let me write the code now. I'll aim for high quality but manageable size.
Frontend components:
- App.jsx — layout shell
- Sidebar.jsx
- TopBar.jsx
- PlayerBar.jsx
- NowPlaying.jsx (immersive panel, full screen overlay)
- QueuePanel.jsx
- TrackRow.jsx
- AlbumCard.jsx
- Views: HomeView, TracksView, AlbumsView, AlbumView, ArtistsView, ArtistView, PlaylistsView, PlaylistView, FavoritesView, SearchView
- Icons from lucide-react
- hooks: useAudioEngine, useDominantColor, useKeyboardShortcuts
- store/player.js, store/library.js, store/ui.js
- lib/api.js, lib/format.js, lib/color.js
That's a lot of files. Let me consolidate views into fewer files to keep it tractable: views/LibraryViews.jsx containing Home, Tracks, Albums, Artists, Favorites, Search; views/DetailViews.jsx for Album/Artist/Playlist. Or one views/index.jsx. I'll do:
- views/HomeView.jsx
- views/TracksView.jsx (also used for favorites/search results with props)
- views/CollectionView.jsx (album/artist/playlist detail)
- views/BrowseView.jsx (albums grid, artists grid)
- views/PlaylistsView.jsx
Hmm. Let me structure cleanly:
views/HomeView.jsxviews/SongsView.jsxviews/AlbumsView.jsxviews/ArtistsView.jsxviews/AlbumDetail.jsxviews/ArtistDetail.jsxviews/PlaylistDetail.jsxviews/PlaylistsView.jsxviews/SearchView.jsx
That's 9 files, each small. OK.
CSS: single styles.css (~1000 lines) with design tokens, layout, components. That's fine and easier to keep coherent than CSS modules.
Let me start writing. First package.json files + install.
Vite 8 requires Node 20.19+ / 22.12+ — we have 25. Good.
React 19.3.1.
Let me use @vitejs/plugin-react latest.
Check plugin version quickly? I'll just use ^6 maybe. Let me install @vitejs/plugin-react latest via npm without version pin and let npm resolve.
Let me write root package.json with workspaces, then server & web package.json, then npm install.
Actually with workspaces, npm install at root installs all.
Let me do it.
For the audio visualizer I'll use Web Audio API with an AnalyserNode, and render bars on canvas with requestAnimationFrame. Need to create MediaElementSource once. Volume controlled via audio element (GainNode not needed).
Cross-origin: same origin through Vite proxy → no CORS taint. Good.
Let me now write all backend files.
Careful about express 5 async error handling: Express 5 handles rejected promises from async handlers automatically.
Range streaming implementation:
router.get('/:id/stream', async (req,res) => {
const track = db().tracks.find(t=>t.id===req.params.id);
if (!track) return res.status(404).json({error:'Track not found'});
const abs = safeJoin(MUSIC_DIR, track.file);
let stat; try { stat = await fs.stat(abs) } catch { return 404 }
const total = stat.size;
const mime = track.mime || mimeFromExt;
res.setHeader('Accept-Ranges','bytes');
res.setHeader('Content-Type', mime);
res.setHeader('Cache-Control','public, max-age=3600');
const etag = `"${track.id}-${Math.floor(stat.mtimeMs)}"`;
if (req.headers['if-none-match']===etag) return res.status(304).end();
res.setHeader('ETag', etag);
const range = req.headers.range;
if (!range) { res.setHeader('Content-Length', total); return pipeline(createReadStream(abs), res) }
const m = /^bytes=(\d*)-(\d*)$/.exec(range.trim());
if (!m) { res.status(416).setHeader('Content-Range',`bytes */${total}`); return res.end() }
let start, end;
if (m[1]==='') { const suffix = Number(m[2]); if(!suffix) 416; start = Math.max(total-suffix,0); end = total-1 }
else { start = Number(m[1]); end = m[2]===''? total-1 : Math.min(Number(m[2]), total-1) }
if (start>end || start>=total) 416
res.status(206);
res.setHeader('Content-Range', `bytes ${start}-${end}/${total}`);
res.setHeader('Content-Length', end-start+1);
const stream = createReadStream(abs,{start,end});
stream.on('error', ...); res.on('close', ()=>stream.destroy());
stream.pipe(res);
});
Use pipeline from stream/promises for no-range. For range, manual pipe with close handler.
HEAD is auto-handled by Express for GET routes.
safeJoin: resolve and ensure startsWith(MUSIC_DIR + sep).
Uploads: multer diskStorage into temp dir, then move to MUSIC_DIR with sanitized unique filename, then parse & add. Use file.originalname sanitized: replace non-alnum. Keep extension validated.
Also allow scanning external MUSIC_DIR.
Playlists: add/remove/reorder tracks.
Let me write now. I'll create files in batches with create_file (multiple calls per response allowed, up to 20).
Batch 1: root package.json, .gitignore, server/package.json, web/package.json, then install.
Let me be careful with concurrently version ^9.
Let me write.