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

Sign-in: Who Comes Aboard

9 min read
In this lesson10

Open lib/session.ts from lesson 8_1 in Cursor. It contains const CURRENT_MEMBER_ID = "redbeard", so anyone who opens Pirate's Cove is the captain. The ranks from lesson 8_3 say who may do what, but the app still doesn't know who is sitting on the other side of the screen. Establishing who the user is is authentication, that is, signing in. Checking what they may do is authorization, which you already have. In this lesson Claude Code adds a real sign-in, and you check that the lock really stands on the server.

What you will learn

  • choose a sign-in library from the current documentation, not from an old tutorial;
  • ask for sign-in with a plan and a secret that Claude never sees;
  • check the session on the server in pages and in API routes;
  • recognise a typical agent mistake: a lock only in the component.

The library: Better Auth

A homemade password system is easy to get wrong, so the Next.js documentation points to ready-made libraries, among them Auth0, Better Auth, Clerk and NextAuth.js. The Auth.js project, formerly NextAuth.js, is now part of Better Auth, and its maintainers recommend Better Auth for new projects. Pirate's Cove goes this way: sign-in with e-mail and password and a SQLite database in a single file, so everything runs on your computer without accounts in external services.

In older tutorials you will meet NextAuth.js: npm install next-auth installs the stable version 4 with the getServerSession function. Auth.js version 5, with a single auth() function in an auth.ts file, is still marked as beta. Tutorials protect pages with a middleware.ts file, which in Next.js 16 is called proxy.ts. When the agent suggests one of these patterns, ask which documentation it took it from.

Request for Claude Code

Sign-in touches many files, so you build it on a separate branch called login, as in lesson 2_9, and you start with a plan, as in lesson 8_1.

Request for Claude Code:

/plan Add e-mail and password sign-in with Better Auth (better-auth
and better-sqlite3), the database in a sqlite.db file, following the
documentation at better-auth.com/docs/integrations/next. Configuration
in lib/auth.ts, route app/api/auth/[...all]/route.ts, client in
lib/auth-client.ts, page app/sign-in/page.tsx. getCurrentMember() from
@lib/session.ts should read the real session on the server and link
the account to a member by e-mail address (lib/crew-accounts.ts).
Without a session the routes in app/api return 401 and the pages
redirect to /sign-in. Do not create or read .env.local, I will fill
it in myself. Prepare .env.example with variable names only.
At the end run tests, lint, types and build.

In the plan check three things: whether sqlite.db goes into .gitignore, who types in the secret, and whether every route in app/api is on the list of changes.

The rule from lesson 8_4 works

The first attempt to create .env.example ended for us in a refusal: File is covered by a Read deny rule in your permission settings and cannot be written.. The pattern Read(./.env.*) also covers the file with names only, and a Read rule blocks writing too. The documentation lets you cut out an exception with a pattern that starts with an exclamation mark, which works like in .gitignore:

{
  "permissions": {
    "deny": ["Read(./.env)", "Read(./.env.*)", "Read(!.env.example)"]
  }
}

The exception works only on rules listed before it in the same file. After this change Write created .env.example, and reading .env.local was still refused. The same trap sits in Git: git check-ignore -v .env.example printed .gitignore:34:.env* for us, so the pattern from create-next-app hides .env.example too. Claude added the line !.env.example to .gitignore.

The secret you type yourself

Better Auth needs two variables. According to the documentation BETTER_AUTH_SECRET is used for encryption and hashing, should have at least 32 characters and high randomness, and you generate it with the command:

openssl rand -base64 32

Run it in a separate terminal tab in Cursor, not through ! in the Claude session: the Claude Code documentation says that the output of a command run with ! goes into the conversation. BETTER_AUTH_URL is the address of the app, locally http://localhost:3000. You type both into .env.local, and .env.example shows only the names.

What Claude wrote: the auth instance

Open lib/auth.ts:

import Database from "better-sqlite3";
import { betterAuth } from "better-auth";

export const auth = betterAuth({
  database: new Database("./sqlite.db"),
  emailAndPassword: {
    enabled: true,
  },
});

betterAuth creates a single object that handles sign-up, sign-in and sessions. better-sqlite3 is the SQLite driver recommended in the Better Auth documentation, and the whole database is the sqlite.db file in the project folder. The tables were created by the command npx auth@latest migrate --yes, which reported the tables user, session, account and verification for us. The password doesn't go into the database as text: for us the account table held a long string of hexadecimal digits in its place, a hash.

Claude Code runs commands such as npm install or this migration after your consent, and in auto mode without asking. That is why you read git diff before the commit: for us better-auth, better-sqlite3 and @types/better-sqlite3 were added to package.json.

The route from the documentation has three lines and handles all addresses under /api/auth:

import { toNextJsHandler } from "better-auth/next-js";
import { auth } from "@/lib/auth";

export const { GET, POST } = toNextJsHandler(auth);

lib/auth-client.ts creates the client with createAuthClient() from better-auth/react. The /sign-in page calls authClient.signIn.email or authClient.signUp.email and on success goes to the rank panel.

What Claude wrote: the session on the server

The most important change is in lib/session.ts:

export async function getCurrentMember(): Promise<Member | null> {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;

  const memberId = crewAccounts.get(session.user.email);
  return memberId ? (findMember(mainServer, memberId) ?? null) : null;
}

headers() from next/headers gives the headers of the current request, including the session cookie, and auth.api.getSession checks it in the database. Without a valid session the function returns null. The account is linked to a server member through a map of addresses in lib/crew-accounts.ts, for example anne@pirates-cove.test is anne.

The Member | null type starts working for you at once. npx tsc --noEmit pointed us to 11 places in 6 files that assumed the member always exists, for example Argument of type 'Member | null' is not assignable to parameter of type 'Member'. Every route got a lock at the start:

const me = await getCurrentMember();
if (!me) {
  return Response.json({ error: "Sign in" }, { status: 401 });
}

Code 401 means "I don't know who you are", and the 403 from lesson 8_3 means "I know, but you are not allowed". Pages, the rank panel included, do redirect("/sign-in") here, and the kick route test got a case "no session 401".

Discord as a second gate

Discord comes in through configuration alone in lib/auth.ts, whenever you want it:

socialProviders: {
  discord: {
    clientId: process.env.DISCORD_CLIENT_ID as string,
    clientSecret: process.env.DISCORD_CLIENT_SECRET as string,
  },
},

According to the Better Auth documentation you register the return address http://localhost:3000/api/auth/callback/discord in the Discord Developer Portal, and in production the same address with your domain. Without these variables the build printed the warning Social provider discord is missing clientId or clientSecret for us.

Captain's review

  1. Secrets outside Git. Before the .gitignore fix the git status --short command showed ?? sqlite.db for us. That file holds accounts and sessions, so it must not reach the repository. After the fix git status shows neither the database nor .env.local.
  2. Direct entry without a session. Open the rank panel in a private window. For us curl -i on that address gave 307 with location: /sign-in, a cookie with a forged token too, and POST /api/members/blackbeard/kick without a cookie got 401 and {"error":"Sign in"}.
  3. Ranks after signing in. Anne, an officer without MANAGE_ROLES, got a 404 on the rank panel, and an attempt to kick the captain ended with 403. The captain saw the panel and kicked Blackbeard.
  4. A typical agent mistake: a lock only in the component. We checked it on a crew list with e-mail addresses that the agent added to the rank panel. A Client Component hid the list when authClient.useSession() had no session, but the data came from a new /api/crew route that didn't check the session. On screen everything looked fine, and curl without a cookie got 200 from that route and the addresses of the whole crew. The Next.js documentation says to treat every API route as a public endpoint, and Better Auth reminds you to check the session on the server for every protected page and action.

At the end run the tests, npm run lint, npx tsc --noEmit after npx next typegen and npm run build. You check the browser steps live: sign-up, sign-in and entering the panel without a session.

Next step

Ask for a commit, for example "Better Auth sign-in, server-side session, 401 in routes". Pirate's Cove now has everything from the map of this location, built in this order: the server model with channels, the voice channel with status, ranks with a lock in the routes, the weather with the key in the hold, and sign-in. If a similar list or another route without a lock appeared in your project, write it down but don't fix it yet: in the next lesson you will check whether a security review finds it on its own.

In the editor below a port simulation with sign-in is waiting: enter the panel without a session, sign in as different pirates and turn on the agent bug in which the crew list has a lock only on the screen.

Remember: the guard at the gangway asks everyone for their name, and a guard painted on the door only looks good.

Code for this lesson: App.jsx
// A port with sign-in: a session cookie, getCurrentMember() and two routes on a pretend server.
// Passwords and accounts are made up; nothing leaves for the network.
import { useState } from 'react';

const crew = [
  { email: 'redbeard@pirates-cove.test', memberId: 'redbeard', name: 'Captain Redbeard', canManageRoles: true },
  { email: 'anne@pirates-cove.test', memberId: 'anne', name: 'Anne Bonny (Officer)', canManageRoles: false },
  { email: 'jack@pirates-cove.test', memberId: 'jack', name: 'Jack Rackham (Crew)', canManageRoles: false },
];

// Server: sessions in a "database" and getCurrentMember as in lib/session.ts.
const sessions = new Map();

function getCurrentMember(cookie) {
  const email = cookie ? sessions.get(cookie) : undefined;
  if (!email) return null;
  return crew.find((c) => c.email === email) ?? null;
}

function rolesPage(cookie) {
  const me = getCurrentMember(cookie);
  if (!me) return { status: 307, body: 'location: /sign-in' };
  if (!me.canManageRoles) return { status: 404, body: 'Page not found' };
  return { status: 200, body: 'Rank panel for: ' + me.name };
}

function crewRoute(cookie, buggy) {
  if (!buggy && !getCurrentMember(cookie)) {
    return { status: 401, body: JSON.stringify({ error: 'Sign in' }) };
  }
  return { status: 200, body: JSON.stringify(crew.map((c) => c.email)) };
}

export default function App() {
  const [cookie, setCookie] = useState(null);
  const [buggy, setBuggy] = useState(true);
  const [answers, setAnswers] = useState([]);

  function signIn(email) {
    const token = 'session-' + email.split('@')[0];
    sessions.set(token, email);
    setCookie(token);
  }

  function request(label, res) {
    setAnswers((prev) => [label + ' β†’ ' + res.status + '  ' + res.body, ...prev].slice(0, 6));
  }

  const me = getCurrentMember(cookie);
  const screenCrew = me ? JSON.parse(crewRoute(cookie, buggy).body) : null;

  return (
    <div className="min-h-screen space-y-4 bg-slate-100 p-4 font-sans text-slate-900">
      <section className="space-y-2 rounded-lg bg-slate-800 p-4 text-slate-100">
        <h1 className="font-bold">Coming aboard</h1>
        <p className="text-sm">Signed in: {me ? me.name : 'nobody'} {cookie ? '(cookie: ' + cookie + ')' : ''}</p>
        <div className="flex flex-wrap gap-2">
          {crew.map((c) => (
            <button key={c.email} onClick={() => signIn(c.email)} className="rounded bg-indigo-600 px-3 py-1 text-sm">Sign in: {c.memberId}</button>
          ))}
          <button onClick={() => setCookie(null)} className="rounded border border-slate-400 px-3 py-1 text-sm">Sign out</button>
        </div>
      </section>

      <section className="rounded-lg border border-slate-300 bg-white p-3">
        <h2 className="font-bold">Screen: the crew list on the panel</h2>
        <p className="text-xs text-slate-500">The component hides the list when useSession() has no session.</p>
        {screenCrew ? (
          <ul className="mt-2 list-disc pl-5 text-sm">{screenCrew.map((e) => <li key={e}>{e}</li>)}</ul>
        ) : (
          <p className="mt-2 text-sm italic">List hidden.</p>
        )}
      </section>

      <label className="flex items-center gap-2 text-sm">
        <input type="checkbox" checked={buggy} onChange={(e) => setBuggy(e.target.checked)} />
        Agent bug: /api/crew does not check the session, the lock stands only in the component
      </label>

      <section className="space-y-2 rounded-lg border border-slate-300 bg-white p-3">
        <h2 className="font-bold">Requests straight to the server</h2>
        <div className="flex flex-wrap gap-2 text-sm">
          <button onClick={() => request('GET /servers/black-pearl/settings/roles', rolesPage(cookie))} className="rounded bg-slate-700 px-3 py-1 text-white">Open the rank panel</button>
          <button onClick={() => request('curl /api/crew (no cookie)', crewRoute(null, buggy))} className="rounded bg-red-600 px-3 py-1 text-white">curl /api/crew without a cookie</button>
          <button onClick={() => request('GET /servers/... with a forged cookie', rolesPage('forged'))} className="rounded bg-slate-700 px-3 py-1 text-white">Forged cookie</button>
        </div>
        <ul className="space-y-1 font-mono text-xs">{answers.map((a, i) => <li key={i}>{a}</li>)}</ul>
      </section>
    </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. How does getCurrentMember() from lib/session.ts establish who is signed in after the sign-in lesson?

  2. 2. What happens when someone without a session opens the address of the rank panel?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the access to the signed-in pirate's address: session.user.email

  • Click in order

    Click to build the server-side session retrieval: await auth.api.getSession({ headers: await headers() })

  • Vertical ordering

    Arrange the order in which Pirate's Cove was built in this location:

  1. QuestionQuiz: The session in getCurrentMember
  2. Put in orderOrdering: The e-mail address from the session
  3. QuestionQuiz: The rank panel without a session
  4. Click in orderOrdering: Getting the session on the server
  5. Put in orderOrdering: Building Pirate's Cove

Useful articles