Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Sessions and Authentication

Login and Logout

Build a login flow in Remix and React Router: a form action, password hashing with scrypt, safe error messages, session creation, redirects, and a logout action.

Authentication in Remix and React Router is not a special feature. It is an ordinary form, an action that checks the credentials, a session that remembers the result and a redirect. Because everything is plain web standards, you can read every step. This lesson builds the login and logout flow in the order it happens, and gives you a runnable stand-in for the part that matters most: verifying passwords safely.

The read-only snippets use React Router framework mode; the same code works in Remix with imports from @remix-run/node. They rely on the session helpers from Cookies and Sessions and Session Storage Options.

The shape of the flow

sequenceDiagram
  participant B as Browser
  participant A as Login action
  participant S as Session store
  B->>A: POST /login (email, password)
  A->>A: validate input, load user, verify hash
  A->>S: new session { userId }
  A-->>B: 302 to /dashboard + Set-Cookie
  B->>A: GET /dashboard (cookie)
  A->>S: read session

The password is sent once, over HTTPS. After that, only the session cookie identifies the visitor.

The login route

TSX
// app/routes/login.tsx (React Router framework mode, read-only)
import { Form, redirect, data } from "react-router";
import type { Route } from "./+types/login";
import { getSession, commitSession } from "~/sessions.server";
import { verifyLogin } from "~/auth.server";

export async function loader({ request }: Route.LoaderArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  if (session.has("userId")) return redirect("/dashboard"); // already signed in
  return data({ error: session.get("error") ?? null }, {
    headers: { "Set-Cookie": await commitSession(session) },
  });
}

export async function action({ request }: Route.ActionArgs) {
  const form = await request.formData();
  const email = String(form.get("email") ?? "").trim().toLowerCase();
  const password = String(form.get("password") ?? "");

  if (!email || !password) {
    return data({ error: "Enter your email and password." }, { status: 400 });
  }

  const user = await verifyLogin(email, password);
  if (!user) {
    // the same message for "no such user" and "wrong password"
    return data({ error: "Email or password is incorrect." }, { status: 401 });
  }

  const session = await getSession(request.headers.get("Cookie"));
  session.set("userId", user.id);
  return redirect("/dashboard", {
    headers: { "Set-Cookie": await commitSession(session) },
  });
}

export default function Login({ actionData }: Route.ComponentProps) {
  return (
    <Form method="post">
      {actionData?.error && <p role="alert">{actionData.error}</p>}
      <label>Email <input name="email" type="email" autoComplete="username" required /></label>
      <label>Password <input name="password" type="password" autoComplete="current-password" required /></label>
      <button type="submit">Sign in</button>
    </Form>
  );
}

Notice the choices:

  • One error message for unknown email and wrong password. Different messages would let attackers discover which emails have accounts.
  • Status codes 400 and 401 on a returned data() keep the form on screen while telling HTTP clients what happened.
  • A redirect after success means a refresh does not re-submit the form (the post/redirect/get pattern).
  • autoComplete values let password managers work.

Storing and checking passwords

Never store a password. Store a slow, salted hash from a function designed for the job: argon2id, bcrypt or scrypt. A fast hash such as plain SHA-256 can be brute-forced at billions of guesses per second. A password hash includes a random salt, so equal passwords produce different hashes, and compares must be constant-time.

Node.js Stand-in: hash and verify with scrypt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Logout

Logging out must destroy the session, not just redirect. It must also be a POST action, never a link, because a GET that changes state can be triggered by any other site (an image tag is enough):

TSX
// app/routes/logout.tsx (read-only)
export async function action({ request }: Route.ActionArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  return redirect("/login", {
    headers: { "Set-Cookie": await destroySession(session) },
  });
}

// anywhere in the UI
<Form method="post" action="/logout">
  <button type="submit">Sign out</button>
</Form>

destroySession returns a Set-Cookie header that expires the cookie. With a database store it also runs your deleteData, so the server-side row disappears too.

Node.js Stand-in: the login and logout state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Registration and password rules

Sign-up uses the same pattern: validate, hash, create the user, create the session, redirect. Enforce a minimum length (at least 8, preferably 12) rather than odd composition rules, check for duplicate emails and return field errors from the action. Add rate limiting to login so one IP cannot try thousands of passwords; see CSRF and Security.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why return the same message for an unknown email and a wrong password?

    Different messages leak whether an account exists (account enumeration).
  2. 2. How should passwords be stored?

    Slow, salted hashes make guessing expensive and keep equal passwords from sharing a hash.
  3. 3. Why is logout a POST action and not a link?

    State changes belong to non-GET methods, which SameSite cookies and CSRF checks can protect.
  4. 4. What is the purpose of redirecting after a successful login action?

    Post/redirect/get turns the result page into a normal GET.

Summary

  • Login is a form, an action, a session and a redirect, all on web standards.
  • Hash passwords with a slow salted algorithm and compare in constant time.
  • Give one generic error for bad credentials; return 400/401 with data().
  • Log out with a POST action that calls destroySession.
  • Rotate the session on login; rate-limit attempts.

Next: Protecting Routes and Authorization