welisten is a music streaming app for listening together with friends. it's built on next.js 13 with the app router, typescript, prisma on postgres, and next-auth for sign in. the ui is shadcn and radix, state is redux toolkit, and the player itself wraps react-h5-audio-player.
sign in works with a magic link over email, google, or discord. next-auth handles all three through its prisma adapter, so users, accounts and sessions are just tables in the same database as everything else. the entire auth configuration is one object.
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(db),
session: { strategy: "jwt" },
providers: [
EmailProvider({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: Number(process.env.EMAIL_SERVER_PORT),
auth: { user: process.env.EMAIL_SERVER_USER, pass: process.env.EMAIL_SERVER_PASSWORD },
},
from: process.env.EMAIL_FROM,
}),
GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_SECRET! }),
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_SECRET!,
authorization: { params: { scope: "identify email" } },
}),
],
};the route handler for it is two lines, since the app router lets the same next-auth handler answer both get and post under /api/auth. the email provider sends its link through nodemailer and the session is a jwt rather than a database row so the play pages don't hit postgres on every request.
the data model is small on purpose: users, artists, songs, friend requests and notifications. a song is a title, a cover, an artist and a url to the audio, and the player streams straight from that url.
model Song {
id String @id @default(cuid())
title String
cover String
artistId String
songUrl String
length String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
artist Artist @relation(fields: [artistId], references: [id])
}playback is driven by a single redux slice that holds the current song. clicking a song card dispatches changeSong with the card's url, title, artist and cover, the now-playing bar at the bottom selects that state, and the audio player is just given the url. there is no player state outside the slice, so any component anywhere in the tree can change what's playing.
export const currentSongSlice = createSlice({
name: "currentSong",
initialState: { url: "", title: "", artist: "", img: "" },
reducers: {
changeSong: (state, action) => {
state.url = action.payload.url;
state.title = action.payload.title;
state.artist = action.payload.artist;
state.img = action.payload.img;
},
},
});
// song-card.tsx
onClick={() => dispatch(changeSong({ url, title, artist, img }))}
// now-playing.tsx
const { url, title, artist, img } = useSelector((state: RootState) => state.currentSong);
<MusicPlayer url={url} />the app is split into route groups: the marketing page, auth, docs, and /play where the actual player lives with a sidebar, search, the now-playing bar, and a grid of songs. there's a per-user page under /play/user and a settings page.
listening with friends
friends can join the same session and hear the same song at the same point in time. the audio itself never passes through the server. each client streams the song from its existing songUrl while a WebSocket connection carries the small bits of information needed to keep everyone in sync.
Socket.IO handles the real-time connection. a user creates a room and shares an invite with friends and everyone who joins subscribes to that room's events. the host controls the queue and playback. pressing play, pausing, seeking, or switching songs sends a command to the server, which checks that the sender is allowed to control the room and broadcasts the new state to its members. NextAuth provides the identity for each connection and Prisma/Postgres stores room membership and invitations so private sessions stay private.
the current playback position is not broadcast every second. instead the server sends a timestamped snapshot whenever something changes. each client calculates where the song should be playing from the snapshot and the elapsed time:
type PlaybackState = {
songId: string | null;
positionSeconds: number;
isPlaying: boolean;
updatedAt: number; // server timestamp in milliseconds
};
function expectedPosition(state: PlaybackState, now = Date.now()) {
const elapsed = state.isPlaying
? Math.max(0, (now - state.updatedAt) / 1000)
: 0;
return state.positionSeconds + elapsed;
}as an example if the host starts a song at 01:20 and another listener receives that event 200 milliseconds later their player starts near 01:20.2 rather than starting at 01:20. the difference between the client's clock and the server's clock is estimated with a ping round-trip measurements on connect. this is so the elapsed-time math holds even when the two clocks disagree.
on the backend the Socket.IO server keeps each connection in its room and broadcasts authoritative playback updates. socket.data.userId is populated by the authentication middleware, isRoomMember and isRoomHost query the room records in Prisma and the map holds the live playback state per room.
// realtime/rooms.ts
import type { Server } from "socket.io";
type Control =
| { roomId: string; type: "play" | "pause" }
| { roomId: string; type: "seek"; positionSeconds: number }
| { roomId: string; type: "song"; songId: string };
const states = new Map<string, PlaybackState>();
export function registerRoomHandlers(io: Server) {
io.on("connection", (socket) => {
const userId = socket.data.userId as string;
socket.on("room:join", async (roomId: string) => {
if (!(await isRoomMember(userId, roomId))) return;
await socket.join(roomId);
const state = states.get(roomId);
if (state) socket.emit("room:state", state);
});
socket.on("room:control", async (command: Control) => {
if (!(await isRoomHost(userId, command.roomId))) return;
const previous = states.get(command.roomId);
if (!previous) return;
const now = Date.now();
const next: PlaybackState = { ...previous };
switch (command.type) {
case "play":
next.positionSeconds = expectedPosition(previous, now);
next.isPlaying = true;
break;
case "pause":
next.positionSeconds = expectedPosition(previous, now);
next.isPlaying = false;
break;
case "seek":
if (!Number.isFinite(command.positionSeconds) || command.positionSeconds < 0) return;
next.positionSeconds = command.positionSeconds;
break;
case "song":
// Validate that the requested song exists and is accessible.
next.songId = command.songId;
next.positionSeconds = 0;
next.isPlaying = true;
break;
}
next.updatedAt = now;
states.set(command.roomId, next);
io.to(command.roomId).emit("room:state", next);
});
});
}the listening room subscribes to room:state and adds those updates to the same player already used throughout the app. a song change still dispatches changeSong to Redux after resolving the song's metadata.
// listening-room.tsx
import type AudioPlayer from "react-h5-audio-player";
const playerRef = useRef<AudioPlayer>(null);
useEffect(() => {
const onRoomState = (state: PlaybackState) => {
const audio = playerRef.current?.audio.current;
if (!audio) return;
// The room's songId must already be resolved to a songUrl,
// and the audio source should be loaded before seeking.
const target = expectedPosition(state);
const drift = Math.abs(audio.currentTime - target);
// Correct noticeable drift without constantly resetting playback.
if (drift > 0.5) audio.currentTime = target;
if (state.isPlaying) {
void audio.play().catch(() => {
// Browsers may require a user gesture before autoplay.
});
} else {
audio.pause();
}
};
// Joining on every connection also handles automatic reconnects.
const joinRoom = () => socket.emit("room:join", roomId);
socket.on("connect", joinRoom);
socket.on("room:state", onRoomState);
if (socket.connected) joinRoom();
return () => {
socket.off("connect", joinRoom);
socket.off("room:state", onRoomState);
};
}, [roomId, socket]);
// When the host presses pause:
socket.emit("room:control", { roomId, type: "pause" });