Skip to the code

Sign in and sign out with a session cookie

Write Leaf and Kettle's sign-in and sign-out, two Server Actions in app/actions.ts.

signIn(previous, formData) runs the sign-in form through useActionState. Read email, trimmed and lowercased, and password, as typed. If either is empty, return { error: "Enter your email and password.", email }.

Check them with checkCredentials(email, password) from @/lib/users, which returns the user, or null when there's no such account or the password is wrong. For null, return { error: "Wrong email or password.", email }: the same words either way, so nobody can use the form to find out who has an account. When the user database is down, checkCredentials throws; then return { error: "We couldn't sign you in. Try again in a minute.", email }. Every error gives back the email, so the form can show it again, and never the password.

For the right user, start a session with createSession(user.id) from @/lib/sessions, and put the token it returns in a session cookie: httpOnly, so scripts on the page can't read it, secure, so it only travels over HTTPS, sameSite: "lax", path: "/", and a week's maxAge, in seconds. Then redirect to /account.

signOut() is the action of the Sign out form on the account page. Read the session cookie, end that session with deleteSession(token), delete the cookie, and redirect to /. Without a cookie, it just redirects.

email " Ana@Example.com ", password "green-tea-42"
→ cookie session=session-1 (httpOnly, secure, sameSite "lax", path "/", maxAge 604800)
→ redirect("/account")
 
email "ana@example.com", password "matcha"
→ { error: "Wrong email or password.", email: "ana@example.com" }

The app's other files

lib/users.ts, read-only. Import it as @/lib/users.

export type User = { id: string; name: string; email: string };
 
type Account = User & { password: string };
 
const accounts: Account[] = [
  { id: "u_ana", name: "Ana", email: "ana@example.com", password: "green-tea-42" },
  { id: "u_ben", name: "Ben", email: "ben@example.com", password: "oolong-at-noon" },
];
 
/** The user database. Tests take it down. */
export const database = { down: false };
 
/**
 * The user with this email and password, or null when there's no such account or the password is
 * wrong. A real shop compares password hashes. Throws when the database can't be reached.
 */
export async function checkCredentials(email: string, password: string): Promise<User | null> {
  if (database.down) throw new Error("The user database is unavailable.");
  const account = accounts.find((entry) => entry.email === email);
  if (!account || account.password !== password) return null;
  return { id: account.id, name: account.name, email: account.email };
}

lib/sessions.ts, read-only. Import it as @/lib/sessions.

/** Live sessions by token: a stand-in for the shop's session store. */
export const sessions = new Map<string, { userId: string }>();
let count = 0;
 
/** Starts a session for the user and returns its token, for the cookie. A real token is long and random. */
export async function createSession(userId: string): Promise<string> {
  count += 1;
  const token = `session-${count}`;
  sessions.set(token, { userId });
  return token;
}
 
/** Ends the session, so its token stops working. An unknown token changes nothing. */
export async function deleteSession(token: string) {
  sessions.delete(token);
}

What the tests check

  1. signs in with a session cookie set safely, then goes to the account page
    const initial = { error: null, email: "" };
    const sent = (request) =>
      request.setCookies.map(({ name, value, httpOnly, secure, sameSite, path, maxAge }) => ({ name, value, httpOnly, secure, sameSite, path, maxAge }));
    await withRequest({ kind: "action" }, async (request) => {
      const where = await redirectOf(() => signIn(initial, formData({ email: "ana@example.com", password: "green-tea-42" })));
      expect(where.url).toBe("/account");
      expect(sent(request)).toEqual([{ name: "session", value: "session-1", httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 604800 }]);
    });
    expect(sessions.get("session-1")).toEqual({ userId: "u_ana" });
    
  2. finds the account whatever the email's case, and spaces around it
    const initial = { error: null, email: "" };
    const sent = (request) =>
      request.setCookies.map(({ name, value, httpOnly, secure, sameSite, path, maxAge }) => ({ name, value, httpOnly, secure, sameSite, path, maxAge }));
    const where = await redirectOf(() => signIn(initial, formData({ email: "  Ben@Example.COM ", password: "oolong-at-noon" })));
    expect(where.url).toBe("/account");
    expect([...sessions.values()]).toEqual([{ userId: "u_ben" }]);
    
  3. gives one message for an unknown email and a wrong password, and keeps the email
    const initial = { error: null, email: "" };
    const sent = (request) =>
      request.setCookies.map(({ name, value, httpOnly, secure, sameSite, path, maxAge }) => ({ name, value, httpOnly, secure, sameSite, path, maxAge }));
    await withRequest({ kind: "action" }, async (request) => {
      expect(await signIn(initial, formData({ email: "ana@example.com", password: "matcha" }))).toEqual({ error: "Wrong email or password.", email: "ana@example.com" });
      expect(await signIn(initial, formData({ email: " Zoe@Example.com", password: "green-tea-42" }))).toEqual({ error: "Wrong email or password.", email: "zoe@example.com" });
      expect(request.setCookies).toEqual([]);
    });
    expect(sessions.size).toBe(0);
    
  4. asks for both fields
    const initial = { error: null, email: "" };
    const sent = (request) =>
      request.setCookies.map(({ name, value, httpOnly, secure, sameSite, path, maxAge }) => ({ name, value, httpOnly, secure, sameSite, path, maxAge }));
    expect(await signIn(initial, formData({ email: "", password: "green-tea-42" }))).toEqual({ error: "Enter your email and password.", email: "" });
    expect(await signIn(initial, formData({ email: "Ana@example.com", password: "" }))).toEqual({ error: "Enter your email and password.", email: "ana@example.com" });
    expect(await signIn(initial, formData({}))).toEqual({ error: "Enter your email and password.", email: "" });
    expect(sessions.size).toBe(0);
    
  5. says to try again while the database is down, and signs in once it's back
    const initial = { error: null, email: "" };
    const sent = (request) =>
      request.setCookies.map(({ name, value, httpOnly, secure, sameSite, path, maxAge }) => ({ name, value, httpOnly, secure, sameSite, path, maxAge }));
    database.down = true;
    expect(await signIn(initial, formData({ email: "ana@example.com", password: "green-tea-42" }))).toEqual({ error: "We couldn't sign you in. Try again in a minute.", email: "ana@example.com" });
    database.down = false;
    const where = await redirectOf(() => signIn(initial, formData({ email: "ana@example.com", password: "green-tea-42" })));
    expect(where.url).toBe("/account");
    
  6. signOut ends the session, deletes the cookie, and goes home
    const token = await createSession("u_ana");
    await withRequest({ kind: "action", cookies: { session: token } }, async (request) => {
      const where = await redirectOf(signOut);
      expect(where.url).toBe("/");
      expect(request.setCookies.map((item) => item.name)).toEqual(["session"]);
      const [cookie] = request.setCookies;
      expect(cookie.value).toBe("");
      expect(cookie.path).toBe("/");
      expect(cookie.maxAge === 0 || cookie.expires?.getTime() === 0).toBe(true);
    });
    expect(sessions.has(token)).toBe(false);
    
  7. signOut without a session still goes home
    const other = await createSession("u_ben");
    await withRequest({ kind: "action" }, async () => {
      expect((await redirectOf(signOut)).url).toBe("/");
    });
    await withRequest({ kind: "action", cookies: { session: "session-404" } }, async () => {
      expect((await redirectOf(signOut)).url).toBe("/");
    });
    expect(sessions.has(other)).toBe(true);
    

Learn more

app/actions.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).