Vibe coding with Claude Code course · Module 9: Discord clone

Servers and Channels: the Guild Map from Plan Mode

10 min read
In this lesson11

Ahoy! The Black Pearl guild has grown to a hundred pirates, and the whole conversation runs in a single chat. The captain's announcements drown between jokes, expedition plans mix with trading, and a new deckhand has no idea who is in charge. In this location you build Pirate's Cove, a community server for the crew modelled on Discord: separate channels for separate matters, roles, and a member list that shows at a glance who is on deck.

What you will learn

  • plan the server data model with Claude Code before a single component exists;
  • read the types one by one in Cursor and check that the plan holds;
  • order the channel bar, the server list and the member list in separate requests;
  • catch in the diff a sort that silently corrupts data, and write the rule into CLAUDE.md.

Discord vs Slack

In Ship's Comms, the Slack clone, you built a workspace for one crew, where conversation happens mostly in writing. Discord was made for communities and gamers: instead of a workspace it has servers, next to the text channels stand always-open voice channels, and roles decide who may do what. Pirate's Cove follows the Discord way.

A new port: the pirates-cove project

Pirate's Cove is a separate app, so you create it with the command from lesson 1_2, changing only the name. Before you click Yes, compare the command with this one:

npx create-next-app@latest pirates-cove --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npm

Then the familiar routine: a session in the pirates-cove folder, a CLAUDE.md that imports @AGENTS.md, Vitest with the @types/node fix from lesson 4_1, and a first commit. None of it is new, so there is nothing to guess here.

The problem: one chat for a hundred pirates

A server is a map. At the top stands the guild, inside it categories, which are groups of channels, and inside the categories the channels: text ones for writing, voice ones for talking, and an announcement channel where only the command writes. Next to the map stand roles and members. If this model is wrong, every component built on it inherits the mistake, which is why you start with a plan. You know plan mode from lesson 2_1: /plan before a request makes Claude study the project and lay out a plan, without touching a single file.

Request for Claude Code:

/plan We are building Pirate's Cove, a Discord clone. Plan the data model
in types/server.ts: a server with an owner, categories and channels
(text, voice, announcement) with a position field, roles with a colour,
a position, an isHoisted flag and a permissions field as a number,
members with a status of online, idle, dnd or offline. Test data in
lib/server-data.ts: the Black Pearl guild and two smaller servers. The
logged-in member from one function in lib/session.ts. Do not write
components yet. Show the types, the files and the order of steps. Ask
questions if anything is missing.

In the plan you check two things. First, categories: in the Discord API a category is also a channel, of type GUILD_CATEGORY, that holds up to 50 channels, and a channel points at its category with the parent_id field. In the clone a simpler form is enough: a separate category type and a categoryId field in the channel. Second, permissions: for now it is a single number in the role, and in lesson 8_3 you will break it into bits. When the plan passes review, choose Yes, manually approve edits so that you approve every edit.

What Claude wrote: the data model

Open types/server.ts in Cursor and read it type by type. At the top stand unions, closed lists of values, and below them the channel:

export type ChannelType = "text" | "voice" | "announcement";
export type Status = "online" | "idle" | "dnd" | "offline";

export interface Channel {
  id: string;
  name: string; // "general", "war-council"
  type: ChannelType;
  categoryId: string | null;
  position: number;
  userLimit?: number; // voice channels only
}

A typo such as "vocie" will not get past the compiler, and categoryId: null means a channel without a category, standing at the very top of the bar. userLimit has a question mark, so it is optional, because a limit on people only makes sense in a voice channel. The statuses come from the Discord documentation: online, idle (be right back), dnd (do not disturb) and offline. A fifth one, invisible, is seen by others as offline, so the clone leaves it out.

A role says how someone looks in the list and what they are allowed to do:

export interface Role {
  id: string;
  name: string;
  color: string; // "#e11d48"
  position: number; // higher number = higher rank
  isHoisted: boolean; // a separate group in the member list
  permissions: number; // permission bits, details in lesson 8_3
}

position sets the hierarchy: a Captain at position 3 stands above an Officer at position 2. isHoisted pulls the members of this role into a separate group in the list instead of mixing them with the rest. The permissions field is for now a plain number, and nothing in this lesson reads it.

At the end of the file stand Member and Server. A member has a username, a unique name such as anne, and a displayName for showing. There is no four-digit tag like #1234: in 2023 Discord began removing those tags in favour of unique names, and an account moved to the new system has just "0" in the discriminator field. The server gathers everything in one object and has an ownerId, because in lesson 8_3 the owner will have special rights.

The channel bar: a separate request

You order each component separately: a small diff reads quickly, and a mistake in it shows at once.

Request for Claude Code:

Build components/ServerSidebar.tsx for the types in @types/server.ts:
the server name, categories sorted by position and collapsible with a
click, in each of them the channels sorted by position with a type icon,
the active channel highlighted, and at the bottom a panel of the
logged-in member. Show the bar on the page
app/servers/[serverId]/[channelId]/page.tsx. At the end lint, types and
build.

What Claude wrote: sorting

Open components/ServerSidebar.tsx. First the order of categories and channels:

const categories = [...server.categories].sort((a, b) => a.position - b.position);

function channelsOf(categoryId: string) {
  return server.channels
    .filter((c) => c.categoryId === categoryId)
    .sort((a, b) => a.position - b.position);
}

[...server.categories] makes a shallow copy of the array and only then sorts it. In channelsOf there is no copy, and rightly so: filter always returns a new array, so sort orders an array that this same code has just created. Newer browsers also have toSorted, which returns a sorted copy straight away.

What Claude wrote: collapsible categories

The file starts with "use client", because the bar reacts to clicks and remembers state, which a Server Component cannot do. Collapsed categories live in state as a set of identifiers:

const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());

function toggle(categoryId: string) {
  setCollapsed((prev) => {
    const next = new Set(prev);
    if (next.has(categoryId)) next.delete(categoryId);
    else next.add(categoryId);
    return next;
  });
}

toggle does not change the old set, it builds a new one and hands it to React, so the component draws again. The category button has aria-expanded={!isCollapsed}, which tells a screen reader whether the list is open, and the channel list renders only when the category is not in the set. The channel type icon (#, a note or an exclamation mark) has hidden text next to it, for example "voice channel", and the panel at the bottom shows a status dot with a hidden description in the same way.

The server list and the member list

Two more requests in the same style produced components/ServerList.tsx and components/MemberList.tsx. The server list has no "use client": it has no state or events, and the active server arrives from the address through props. Each icon is a Link with the guild's initials, a title with the full name, and a bar on the left for the active server.

The member list groups the crew with the groupMembers function from lib/members.ts. It all starts from a member's highest role:

export function getHighestRole(member: Member, roles: Role[]): Role | null {
  const own = roles.filter((role) => member.roleIds.includes(role.id));
  own.sort((a, b) => b.position - a.position);
  return own[0] ?? null;
}

The function takes the member's roles, orders them descending by position and returns the first one, or null. groupMembers puts every member who is not offline into the group of their highest isHoisted role, the rest into the "Online" group, and everyone with the offline status last, into "Offline". Ours showed in order: CAPTAIN - 1, OFFICER - 1, ONLINE - 2 and OFFLINE - 1.

Captain's review

  1. A copy before sorting. A typical agent mistake is server.categories.sort(...) without [...]. MDN says outright that sort() sorts the array in place and returns the same array, and the React documentation says props are immutable, never change them. So in the diff you look for every .sort( and .reverse( on data from props. Ours passed npm run lint and npx tsc --noEmit without a word in that version, so also ask for a test that records the category order, draws the bar and compares the data (the result is below the list).
  2. Unions instead of strings. type and status should be unions, not string.
  3. position really steers. In the test data the voice category stands before the text one, and position says the opposite. On the page TEXT CHANNELS should come first, and in ours it did.
  4. Proof. Tests, npm run lint, npx tsc --noEmit and npm run build. Before the first build tsc does not know PageProps<"/servers/[serverId]/[channelId]">; route types are generated by npx next typegen.

The test result with the version without a copy, that is with server.categories.sort(...), looked like this for us:

FAIL  components/ServerSidebar.test.tsx > does not change the category order in the server data
AssertionError: expected [ 'text', 'voice' ] to deeply equal [ 'voice', 'text' ]

With the copy the test passes, without it it fails. The server data changed just from being displayed, and in a Server Component such a change would reach data shared by all requests.

Next step: a rule in CLAUDE.md

This mistake keeps coming back, because sort looks innocent. Ask Claude for one line in CLAUDE.md:

- Data from props and lib/ is read-only: sort a copy ([...list].sort), never the list in place.

According to the Claude Code documentation CLAUDE.md is loaded at the start of every session, but Claude treats it as guidance, not a hard rule, and the more concrete the line, the more reliably it listens. That is why you keep the test too: the line prevents the mistake, the test catches it. Then ask for a commit, for example "Server model, channel bar, server and member lists".

In the editor below a miniature guild is waiting: collapse categories, switch servers and turn on the agent bug to see how the order in the data changes from the drawing alone.

Remember: the captain draws the map before the crew starts digging, and a good map does not change just because someone looked at it.

Code for this lesson: App.jsx
// Pirate's Cove in miniature: servers, collapsible categories and a member list.
// In the project the data lives in lib/server-data.ts and the components in components/.
// The "agent bug" switch sorts the categories in place, like server.categories.sort(...).
import { useState } from 'react';

const servers = [
  {
    id: 'black-pearl',
    name: 'Black Pearl Guild',
    categories: [
      { id: 'voice', name: 'VOICE CHANNELS', position: 1 },
      { id: 'text', name: 'TEXT CHANNELS', position: 0 },
    ],
    channels: [
      { id: 'treasure-hunts', name: 'treasure-hunts', type: 'text', categoryId: 'text', position: 2 },
      { id: 'general', name: 'general', type: 'text', categoryId: 'text', position: 1 },
      { id: 'announcements', name: 'announcements', type: 'announcement', categoryId: 'text', position: 0 },
      { id: 'war-council', name: 'war-council', type: 'voice', categoryId: 'voice', position: 0 },
      { id: 'mess', name: 'mess', type: 'voice', categoryId: 'voice', position: 1 },
    ],
    roles: [
      { id: 'crew', name: 'Crew', color: '#64748b', position: 1, isHoisted: false },
      { id: 'captain', name: 'Captain', color: '#e11d48', position: 3, isHoisted: true },
      { id: 'officer', name: 'Officer', color: '#2563eb', position: 2, isHoisted: true },
    ],
    members: [
      { id: 'redbeard', displayName: 'Captain Redbeard', roleIds: ['captain', 'crew'], status: 'online' },
      { id: 'anne', displayName: 'Anne Bonny', roleIds: ['officer', 'crew'], status: 'online' },
      { id: 'jack', displayName: 'Jack Rackham', roleIds: ['crew'], status: 'idle' },
      { id: 'mary', displayName: 'Mary Read', roleIds: ['officer', 'crew'], status: 'offline' },
      { id: 'blackbeard', displayName: 'Blackbeard', roleIds: ['crew'], status: 'dnd' },
    ],
  },
  {
    id: 'tortuga',
    name: 'Tortuga Market',
    categories: [{ id: 'trade', name: 'TRADE', position: 0 }],
    channels: [{ id: 'prices', name: 'prices', type: 'text', categoryId: 'trade', position: 0 }],
    roles: [],
    members: [],
  },
  {
    id: 'kraken',
    name: 'Kraken Hunters',
    categories: [],
    channels: [{ id: 'tracks', name: 'tracks', type: 'text', categoryId: null, position: 0 }],
    roles: [],
    members: [],
  },
];

const icons = { text: '#', voice: '♪', announcement: '!' };
const typeLabels = { text: 'text channel', voice: 'voice channel', announcement: 'announcement channel' };
const dotColors = { online: 'bg-green-500', idle: 'bg-yellow-400', dnd: 'bg-red-500', offline: 'bg-gray-500' };
const statusLabels = { online: 'online', idle: 'be right back', dnd: 'do not disturb', offline: 'offline' };

function getHighestRole(member, roles) {
  const own = roles.filter((role) => member.roleIds.includes(role.id));
  own.sort((a, b) => b.position - a.position);
  return own[0] || null;
}

function groupMembers(members, roles) {
  const hoisted = roles.filter((role) => role.isHoisted);
  const byRole = [...hoisted]
    .sort((a, b) => b.position - a.position)
    .map((role) => ({ id: role.id, label: role.name, members: [] }));
  const online = { id: 'online', label: 'Online', members: [] };
  const offline = { id: 'offline', label: 'Offline', members: [] };
  for (const member of members) {
    const top = getHighestRole(member, hoisted);
    const group = member.status === 'offline' ? offline : byRole.find((g) => top && g.id === top.id) || online;
    group.members.push(member);
  }
  return [...byRole, online, offline].filter((g) => g.members.length > 0);
}

function initials(name) {
  return name.split(' ').map((word) => word[0]).join('').slice(0, 2).toUpperCase();
}

function StatusDot({ status }) {
  return (
    <>
      <span aria-hidden="true" className={'inline-block h-2.5 w-2.5 shrink-0 rounded-full ' + dotColors[status]} />
      <span className="sr-only">({statusLabels[status]})</span>
    </>
  );
}

export default function App() {
  const [serverId, setServerId] = useState('black-pearl');
  const [channelId, setChannelId] = useState('general');
  const [collapsed, setCollapsed] = useState(() => new Set());
  const [buggy, setBuggy] = useState(false);
  const server = servers.find((s) => s.id === serverId);

  const dataBefore = server.categories.map((c) => c.id).join(', ');
  const categories = buggy
    ? server.categories.sort((a, b) => a.position - b.position) // bug: sorts the data in place
    : [...server.categories].sort((a, b) => a.position - b.position);
  const dataAfter = server.categories.map((c) => c.id).join(', ');

  function toggle(id) {
    setCollapsed((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function resetData() {
    servers[0].categories = [
      { id: 'voice', name: 'VOICE CHANNELS', position: 1 },
      { id: 'text', name: 'TEXT CHANNELS', position: 0 },
    ];
    setBuggy(false);
  }

  function renderChannel(channel) {
    const active = channel.id === channelId;
    return (
      <li key={channel.id}>
        <button
          onClick={() => setChannelId(channel.id)}
          aria-current={active ? 'page' : undefined}
          className={'flex w-full items-center gap-2 rounded px-2 py-1 text-left text-sm ' + (active ? 'bg-gray-700 text-white' : 'text-gray-300 hover:bg-gray-700')}
        >
          <span aria-hidden="true" className="w-4 text-center text-gray-400">{icons[channel.type]}</span>
          <span className="sr-only">{typeLabels[channel.type]}</span>
          {channel.name}
        </button>
      </li>
    );
  }

  const loose = server.channels.filter((c) => c.categoryId === null);

  return (
    <div className="min-h-screen bg-gray-700 text-gray-100">
      <div className="flex flex-wrap items-center gap-3 bg-gray-900 p-2 text-xs">
        <label className="flex items-center gap-1">
          <input type="checkbox" checked={buggy} onChange={(e) => setBuggy(e.target.checked)} />
          Agent bug: server.categories.sort(...) without a copy
        </label>
        <span>Data before render: {dataBefore}</span>
        <span>after render: {dataAfter}</span>
        <button onClick={resetData} className="rounded bg-gray-700 px-2 py-1">Restore data</button>
      </div>

      <div className="flex h-[520px]">
        <nav aria-label="Servers" className="flex w-16 flex-col items-center gap-2 bg-gray-950 py-3">
          {servers.map((s) => (
            <button
              key={s.id}
              title={s.name}
              aria-label={s.name}
              aria-current={s.id === serverId ? 'page' : undefined}
              onClick={() => {
                setServerId(s.id);
                setChannelId(s.channels[0].id);
              }}
              className={'flex h-11 w-11 items-center justify-center font-bold ' + (s.id === serverId ? 'rounded-2xl bg-indigo-500' : 'rounded-full bg-gray-700 hover:rounded-2xl')}
            >
              {initials(s.name)}
            </button>
          ))}
        </nav>

        <nav aria-label="Server channels" className="flex w-56 flex-col bg-gray-800">
          <h2 className="border-b border-gray-900 px-3 py-2 font-bold">{server.name}</h2>
          <div className="flex-1 overflow-y-auto p-2">
            <ul>{loose.map(renderChannel)}</ul>
            {categories.map((category) => {
              const isCollapsed = collapsed.has(category.id);
              const channels = server.channels
                .filter((c) => c.categoryId === category.id)
                .sort((a, b) => a.position - b.position);
              return (
                <section key={category.id} className="mt-2">
                  <button
                    onClick={() => toggle(category.id)}
                    aria-expanded={!isCollapsed}
                    className="flex w-full items-center gap-1 text-xs font-semibold text-gray-400 hover:text-gray-200"
                  >
                    <span aria-hidden="true">{isCollapsed ? '▸' : '▾'}</span>
                    {category.name}
                  </button>
                  {!isCollapsed && <ul className="mt-1">{channels.map(renderChannel)}</ul>}
                </section>
              );
            })}
          </div>
        </nav>

        <main className="flex-1 p-4 text-sm text-gray-300">
          Channel: <strong>{channelId}</strong>. Collapse a category, switch the server, then turn on the agent bug and switch channels a few times.
        </main>

        <aside aria-label="Members" className="w-48 overflow-y-auto bg-gray-800 p-3">
          {groupMembers(server.members, server.roles).map((group) => (
            <section key={group.id} className="mb-3">
              <h3 className="text-xs font-semibold uppercase text-gray-400">{group.label} - {group.members.length}</h3>
              <ul>
                {group.members.map((member) => {
                  const role = getHighestRole(member, server.roles);
                  return (
                    <li key={member.id} className={'flex items-center gap-2 text-sm ' + (member.status === 'offline' ? 'opacity-50' : '')}>
                      <StatusDot status={member.status} />
                      <span style={{ color: role ? role.color : undefined }}>{member.displayName}</span>
                    </li>
                  );
                })}
              </ul>
            </section>
          ))}
          {server.members.length === 0 && <p className="text-xs text-gray-400">This server has no crew yet.</p>}
        </aside>
      </div>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the Server object in the Pirate's Cove data model contain?

  2. 2. How is the channel type written in types/server.ts?

These are 2 of 7 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the steps of work on the Pirate's Cove data model in the order from the lesson:

  • Code editor

    Discord server navigation

  • Click in order

    Click to build the category sort that does not change the data from props: [...server.categories].sort((a, b) => a.position - b.position)

  • Code editor

    Server switcher sidebar

  • Horizontal ordering

    Arrange the line that keeps collapsed categories in state: const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());

  • Vertical ordering

    Arrange the member list groups (MemberList) from the top, when the Captain (position 3) and Officer (position 2) roles have isHoisted: true:

  • Horizontal ordering

    Arrange the last line of the getHighestRole function: return own[0] ?? null;

  • Click in order

    Click to build the category button attribute that tells a screen reader whether the list is expanded:

  1. QuestionQuiz: What a server contains
  2. QuestionQuiz: Channel type
  3. QuestionQuiz: Member status
  4. Put in orderOrdering: Order of work on the model
  5. Coding taskPractice: Server sidebar
  6. QuestionQuiz: Channel and category
  7. QuestionQuiz: The isHoisted field in Role
  8. Click in orderOrdering: Sorting a copy
  9. QuestionQuiz: Sorting data from props
  10. Coding taskPractice: Server list
  11. Put in orderOrdering: State of collapsed categories
  12. QuestionQuiz: getHighestRole
  13. Put in orderOrdering: Groups in the member list
  14. Put in orderOrdering: Returning the highest role
  15. Click in orderOrdering: The aria-expanded attribute

Useful articles