Chrysolites Tech Academy

Building React Apps: Weather, Music and Video · Course book

Chapter 3: A Full-Stack Music Platform

Pairs with Lesson 3: A Full-Stack Music Platform with the MERN Stack

The previous project borrowed its music from someone else's API. A real streaming platform owns its catalogue: administrators upload songs and albums, the server stores them and controls who can change them, listeners browse and play them, and friends can see what each other are listening to and chat in real time. This chapter explains how such a platform is built with the MERN stack, MongoDB, Express, React and Node.js, plus Clerk for authentication, Cloudinary for files and Socket.IO for real-time features. It covers the data model, the API and its middleware, the admin dashboard, the listening interface and its queue, real-time activity and chat, and deployment, with the key logic worked through by hand.

The data model and the API

The back end is an Express server with a MongoDB database accessed through Mongoose. Four collections hold the data.

ModelMain fieldsNotes
UserfullName, imageUrl, clerkIdCreated the first time someone signs in
Songtitle, artist, imageUrl, audioUrl, duration, albumIdalbumId may be empty for singles
Albumtitle, artist, imageUrl, releaseYear, songssongs is a list of Song ids
MessagesenderId, receiverId, content, timestampsStores chat history

Routes are grouped by area: /api/auth for syncing accounts, /api/users for listing users and messages, /api/songs and /api/albums for the catalogue, /api/stats for dashboard numbers and /api/admin for creating and deleting songs and albums. Each route is handled by a controller function, kept in its own file, which keeps the route definitions short and readable. Errors are passed to one shared error-handling middleware with next(error), so every failure produces a consistent JSON response and, in production, hides internal details from the client.

Some lists are computed rather than stored. "Featured" songs might be a random sample, drawn with MongoDB's $sample aggregation stage, so the home page changes from visit to visit, while "made for you" and "trending" sections can use different samples or rules. The stats route counts songs, albums, users and unique artists, using several queries run in parallel with Promise.all so the dashboard loads in the time of the slowest query rather than the sum of all of them.

Authentication and protected routes

Clerk handles sign-in on the front end, including sign-in with Google. After the provider redirects back, a callback page calls the sync route, which creates a User document if one does not exist for this Clerk id, then sends the user to the home page. An auth provider component wraps the app, obtains a fresh token from Clerk and attaches it to every API request through a configured axios instance.

On the server, two middleware functions guard routes. protectRoute checks that the request carries a valid Clerk session and rejects it with 401 Unauthorized otherwise. requireAdmin runs after it and compares the user's email with an administrator address stored in an environment variable, returning 403 Forbidden for everyone else. Chaining them, router.use(protectRoute, requireAdmin), protects every admin route at once. The front end also hides the admin link from non-admins, but that is only a convenience; the middleware is what enforces the rule.

Creating a song is an admin action that accepts files. The request contains the title, artist, an optional album and two files, the audio and the cover image. The controller uploads both to Cloudinary, which returns their addresses, and saves a Song document with those addresses. If the song belongs to an album, the song's id is also pushed into the album's songs list. Deleting reverses both steps, removing the id from the album before deleting the song, so the two never disagree.

The listening interface and the queue

The main layout has three resizable panels: a left sidebar with navigation and the list of albums, the main content in the centre and a friends activity panel on the right, plus a playback bar along the bottom. A resizable-panels library lets users drag the dividers, and the side panels collapse on small screens. The album page shows the cover, title, artist and year, and a table of songs with their number, title, release date and duration, with a large play button for the whole album.

Player state lives in a small global store, for example built with Zustand: the current song, whether it is playing, the queue of songs and the current index. Playing an album sets the queue to its songs and starts at the chosen index; next and previous move through the queue; and when a song ends, an event listener on the audio element plays the next one automatically. A single <audio> element, rendered once in the layout and controlled through a ref, avoids two songs ever playing at the same time.

Worked example. An album has five songs of 214, 187, 243, 199 and 228 seconds. Its total length is 1,071 seconds, which is 17 minutes and 51 seconds, since 17 × 60 = 1,020 and 1,071 − 1,020 = 51. Playing the album from song 3 sets the queue to all five songs with index 2. When song 3 ends, the index moves to 3; after song 5, at index 4, the next index would be 5, which is past the end, so playback stops, or wraps to index 0 if repeat is switched on. Seeking to 2:30 in song 3 sets the audio's current time to 150 seconds, 150 / 243 = 62 percent of the way along the progress bar.

The playback controls show the song's picture and title, previous, play or pause and next buttons, a progress slider with elapsed and total times, and a volume slider. The home page greets the user according to the time of day and shows the featured, made-for-you and trending sections, each a grid of cards with a play button that appears on hover.

Real-time activity and chat with Socket.IO

Ordinary HTTP requests only flow from client to server, so a page cannot learn about new events unless it asks. Asking repeatedly, called polling, is wasteful. WebSockets keep one connection open in both directions, so the server can push events the moment they happen. Socket.IO builds on WebSockets with automatic reconnection and named events.

polling every 5 s: 120 WebSocket: about 11 060120 0510 minutesmessages per user
Figure 3.1 — Polling every 5 seconds sends 12 requests a minute whether or not anything changed; a WebSocket sends one message per real event, here about one a minute.

When a signed-in user opens the app, the client connects and emits a "user connected" event with the user's id. The server keeps a map from user ids to socket ids and broadcasts the updated list of online users to everyone. When someone starts a song, the client emits an activity update such as "Playing: title by artist", and the server broadcasts it, so the friends activity panel shows who is online and what they are playing. On disconnect, the server removes the user from the map and broadcasts again.

Chat uses the same connection. Sending a message emits an event with the receiver's id and the text; the server saves a Message document, looks up the receiver's socket id in the map and, if the receiver is online, emits the message directly to that socket, and also confirms it back to the sender. Opening a conversation loads the earlier history through an ordinary API request, after which new messages arrive in real time.

Admin dashboard, 404 page and deployment

The admin page shows statistics cards, the counts from the stats route, and tabs for songs and albums. Each tab lists the items in a table with delete buttons and offers a dialog for adding a new one, with file pickers for the audio and image and, for songs, a drop-down to choose an album. After a successful upload, the lists and stats are refreshed. A custom 404 page catches unknown routes with a friendly message and a link home.

In production, the Express server can also serve the built React files, so the whole app runs as one service at one address, which avoids cross-origin configuration and lets Socket.IO share the same server. Environment variables hold the database address, the Clerk and Cloudinary keys and the admin email. A scheduled clean-up job can delete temporary upload files so they do not fill the server's disk. Testing the deployed app end to end, signing in, playing, uploading as admin and chatting between two browsers, confirms that every part works together. Watching the server logs during these tests often reveals warnings that never appear in the browser.

Practice tasks

  1. An album's songs last 205, 176, 232 and 251 seconds. Give its total length in minutes and seconds.
  2. A queue has 8 songs and the current index is 7 with repeat off. What happens when the song ends? And with repeat on?
  3. With 200 users online, how many requests per minute does polling every 5 seconds create, compared with a WebSocket design where each user causes about one event a minute?
  4. Explain the order of the two admin middleware functions and why the check must happen on the server.
  5. Describe the steps the server takes when one user sends a chat message to another who is offline.
  6. Why is a song's id removed from its album before the song is deleted?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.