Polski

Tutorial · Authentication · React

Login and registration in React – forms, tokens, protected routes and session refresh

A complete authentication frontend in React 19 – login and registration forms with validation, an access token in memory and a refresh token in an httpOnly cookie, session restore, protected routes, retrying requests after a 401, password reset and Google sign-in – with a working demo API.

By · · 31 min read

A login form is a couple of fields and a button, but behind it sit several decisions that security depends on: where to keep the token, what to do when it expires halfway through placing an order, how to restore the session after a page reload, and how not to reveal whether an email has an account. In this guide you'll build a complete authentication frontend for the dumpling shop app – with a small Express API, so everything works right after npm run dev.

Prerequisites: React with hooks, react-hook-form and TanStack Query (see the React guide), HTTP basics (headers, cookies, status codes). We cover the backend only as far as the frontend needs – details in the Authentication topic.

30 s
access token lifetime in the demo – so you can watch the refresh live
0
tokens in localStorage – access in memory, refresh in an httpOnly cookie
1
/refresh call – even when 10 requests get a 401 at once
9
flows tested in a browser – from registration to Google sign-in

Where to keep tokens

LocationXSS resistanceCSRFSession after reloadVerdict
localStorage / sessionStoragenone – any script can read the tokenno riskyesconvenient, but the token leaks on the first XSS
a plain cookie (no httpOnly)noneneeds protectionyesthe worst of both worlds
access in memory + refresh in an httpOnly cookierefresh unreadable by JS, access short-livedSameSite=Strict + /api/auth pathyes, via /refresha good trade-off for SPAs – this guide
server session / BFF (httpOnly cookie only)the token never reaches the browserneeds protectionyesthe most secure, needs a backend-for-frontend
Diagram: Login, access token expiry and a silent refresh

Step 1. Project and the demo API

npm create vite@latest pierogi-auth -- --template react-ts
cd pierogi-auth
npm install react-router @tanstack/react-query react-hook-form @hookform/resolvers zod
npm install -D express cookie-parser @types/express @types/cookie-parser @types/node

The Express app is plugged into the Vite dev server as middleware (configureServer). Frontend and API share an origin, so cookies work without any CORS setup. In production the same Express app (or your NestJS, .NET or Go backend) sits behind the same reverse proxy as the frontend.

Project configuration

package.json
{
  "name": "pierogi-auth",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build"
  },
  "dependencies": {
    "@hookform/resolvers": "^7.0.9",
    "@tanstack/react-query": "^5.108.4",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "react-hook-form": "^7.92.0",
    "react-router": "^8.5.3",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/cookie-parser": "^1.4.10",
    "@types/express": "^5.0.6",
    "@types/node": "^24.0.0",
    "@types/react": "^19.3.0",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "cookie-parser": "^1.4.7",
    "express": "^5.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client", "node"],
    "jsx": "react-jsx",
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src", "server", "vite.config.ts"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { createAuthApi } from "./server/auth-api.ts";

// The demo API runs inside the Vite dev server (same origin = simple cookies, no CORS).
// In production the same Express app runs on its own behind your reverse proxy.
export default defineConfig({
  plugins: [
    react(),
    {
      name: "auth-api",
      configureServer(server) {
        server.middlewares.use(createAuthApi());
      },
    },
  ],
});
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogarnia · Account</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
src/index.css
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; color: #1f2328; background: #f6f7f9; }
a { color: #c2255c; }
.shell { max-width: 720px; margin: 0 auto; padding: 16px; }
.topbar { display: flex; gap: 16px; align-items: center; padding: 12px 0 16px; border-bottom: 1px solid #dee2e6; margin-bottom: 24px; }
.topbar .spacer { flex: 1; }
.card { background: #fff; border: 1px solid #dee2e6; border-radius: 12px; padding: 24px; max-width: 420px; margin: 0 auto; display: grid; gap: 14px; }
.field { display: grid; gap: 4px; }
.field input { padding: 9px 10px; border: 1px solid #ced4da; border-radius: 8px; font: inherit; }
.field input[aria-invalid="true"] { border-color: #c92a2a; }
.password { display: grid; grid-template-columns: 1fr auto; gap: 6px; }
.error { color: #c92a2a; font-size: 0.875rem; margin: 0; }
.notice { background: #ebfbee; border: 1px solid #b2f2bb; padding: 10px 12px; border-radius: 8px; margin: 0; }
.alert { background: #fff5f5; border: 1px solid #ffc9c9; padding: 10px 12px; border-radius: 8px; margin: 0; }
.muted { color: #6c757d; font-size: 0.875rem; }
button, .button { padding: 9px 14px; border-radius: 8px; border: 1px solid #c2255c; background: #c2255c; color: #fff; font: inherit; cursor: pointer; text-decoration: none; text-align: center; }
button.secondary, .button.secondary { background: #fff; color: #1f2328; border-color: #ced4da; }
button:disabled { opacity: 0.6; cursor: wait; }
.divider { display: flex; align-items: center; gap: 8px; color: #6c757d; font-size: 0.875rem; }
.divider::before, .divider::after { content: ""; flex: 1; border-top: 1px solid #dee2e6; }

The API is production-shaped even though it stores data in memory: passwords hashed with scrypt, the access token in the JSON response, the refresh token in an httpOnly + SameSite=Strict + path=/api/auth cookie, refresh-token rotation on every refresh, and a password reset that signs the user out on all devices.

Express: register, login, refresh, password reset, OAuth

server/auth-api.ts
// A minimal, in-memory auth API for the tutorial. The flows and cookie flags are production-shaped;
// the storage (Maps) and the fake Google provider are not.
import cookieParser from "cookie-parser";
import express, { type NextFunction, type Request, type Response } from "express";
import { randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";

type User = { id: string; name: string; email: string; passwordHash: string | null };
type Grant = { userId: string; expiresAt: number };

const usersByEmail = new Map<string, User>();
const accessTokens = new Map<string, Grant>();
const refreshTokens = new Map<string, Grant>();
const resetTokens = new Map<string, Grant>();

const ACCESS_TTL_MS = 30_000; // deliberately short: watch the silent refresh in the Network tab
const REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const REFRESH_COOKIE = "refresh_token";

function hashPassword(password: string): string {
  const salt = randomBytes(16);
  return `${salt.toString("hex")}:${scryptSync(password, salt, 32).toString("hex")}`;
}

function verifyPassword(password: string, stored: string | null): boolean {
  const [salt, hash] = (stored ?? "").split(":");
  if (!salt || !hash) return false;
  return timingSafeEqual(Buffer.from(hash, "hex"), scryptSync(password, Buffer.from(salt, "hex"), 32));
}

const publicUser = (u: User) => ({ id: u.id, name: u.name, email: u.email });
const findUserById = (id: string) => [...usersByEmail.values()].find((u) => u.id === id);

// Access token goes into the JSON body (kept in memory by the SPA);
// refresh token goes into an httpOnly cookie that JavaScript can't read.
function issueSession(res: Response, user: User) {
  const accessToken = randomUUID();
  accessTokens.set(accessToken, { userId: user.id, expiresAt: Date.now() + ACCESS_TTL_MS });
  const refreshToken = randomBytes(32).toString("base64url");
  refreshTokens.set(refreshToken, { userId: user.id, expiresAt: Date.now() + REFRESH_TTL_MS });
  res.cookie(REFRESH_COOKIE, refreshToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    path: "/api/auth", // the cookie is sent only to auth endpoints
    maxAge: REFRESH_TTL_MS,
  });
  return { accessToken, expiresIn: ACCESS_TTL_MS / 1000, user: publicUser(user) };
}

function requireAuth(req: Request, res: Response, next: NextFunction) {
  const token = req.headers.authorization?.replace(/^Bearer /, "");
  const grant = token ? accessTokens.get(token) : undefined;
  if (!grant || grant.expiresAt < Date.now()) {
    res.status(401).json({ code: grant ? "TOKEN_EXPIRED" : "UNAUTHORIZED", message: "Authentication required" });
    return;
  }
  res.locals.userId = grant.userId;
  next();
}

export function createAuthApi() {
  const app = express();
  app.use("/api", express.json(), cookieParser());

  app.post("/api/auth/register", (req, res) => {
    const { name, email, password } = req.body as { name?: string; email?: string; password?: string };
    if (!name || !email || !password || password.length < 10) {
      res.status(400).json({ code: "VALIDATION_FAILED", message: "Invalid data" });
      return;
    }
    const key = email.toLowerCase();
    if (usersByEmail.has(key)) {
      res.status(409).json({ code: "EMAIL_TAKEN", message: "An account with this email already exists" });
      return;
    }
    const user: User = { id: randomUUID(), name, email: key, passwordHash: hashPassword(password) };
    usersByEmail.set(key, user);
    res.status(201).json(issueSession(res, user));
  });

  app.post("/api/auth/login", (req, res) => {
    const { email, password } = req.body as { email?: string; password?: string };
    const user = usersByEmail.get((email ?? "").toLowerCase());
    // Same error for "no such user" and "wrong password" – no account enumeration.
    if (!user || !verifyPassword(password ?? "", user.passwordHash)) {
      res.status(401).json({ code: "INVALID_CREDENTIALS", message: "Wrong email or password" });
      return;
    }
    res.json(issueSession(res, user));
  });

  // Rotation: every refresh invalidates the old refresh token and sets a new cookie.
  app.post("/api/auth/refresh", (req, res) => {
    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];
    const grant = token ? refreshTokens.get(token) : undefined;
    if (token) refreshTokens.delete(token);
    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;
    if (!user) {
      res.clearCookie(REFRESH_COOKIE, { path: "/api/auth" });
      res.status(401).json({ code: "NO_SESSION", message: "Please sign in" });
      return;
    }
    res.json(issueSession(res, user));
  });

  app.post("/api/auth/logout", (req, res) => {
    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];
    if (token) refreshTokens.delete(token);
    res.clearCookie(REFRESH_COOKIE, { path: "/api/auth" });
    res.status(204).end();
  });

  // Always 204 – the response must not reveal whether the email has an account.
  app.post("/api/auth/forgot-password", (req, res) => {
    const user = usersByEmail.get(String(req.body?.email ?? "").toLowerCase());
    if (user) {
      const token = randomBytes(32).toString("base64url");
      resetTokens.set(token, { userId: user.id, expiresAt: Date.now() + 30 * 60_000 });
      console.log(`[mail] Reset link for ${user.email}: http://localhost:5173/reset-password?token=${token}`);
    }
    res.status(204).end();
  });

  app.post("/api/auth/reset-password", (req, res) => {
    const { token, password } = req.body as { token?: string; password?: string };
    const grant = token ? resetTokens.get(token) : undefined;
    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;
    if (!user || !password || password.length < 10) {
      res.status(400).json({ code: "INVALID_TOKEN", message: "The link is invalid or has expired" });
      return;
    }
    resetTokens.delete(token!);
    user.passwordHash = hashPassword(password);
    for (const [t, g] of refreshTokens) if (g.userId === user.id) refreshTokens.delete(t); // sign out everywhere
    res.status(204).end();
  });

  // Fake "Sign in with Google": a real app redirects to the provider with `state` + PKCE here.
  app.get("/api/auth/google", (_req, res) => {
    const state = randomBytes(16).toString("base64url");
    res.cookie("oauth_state", state, { httpOnly: true, sameSite: "lax", path: "/api/auth", maxAge: 5 * 60_000 });
    res.redirect(`/api/auth/google/callback?code=demo-code&state=${state}`);
  });

  app.get("/api/auth/google/callback", (req, res) => {
    if (!req.query.state || req.query.state !== req.cookies?.oauth_state) {
      res.redirect("/login?error=oauth_state");
      return;
    }
    res.clearCookie("oauth_state", { path: "/api/auth" });
    // Here the server exchanges `code` for the provider's tokens and reads the verified email.
    const email = "halina.demo@gmail.example";
    let user = usersByEmail.get(email);
    if (!user) {
      user = { id: randomUUID(), name: "Halina (Google)", email, passwordHash: null };
      usersByEmail.set(email, user);
    }
    issueSession(res, user); // sets the refresh cookie – no tokens in the URL
    res.redirect("/auth/callback");
  });

  app.get("/api/me", requireAuth, (_req, res) => {
    const user = findUserById(String(res.locals.userId));
    res.json(user ? publicUser(user) : null);
  });

  app.get("/api/orders", requireAuth, (_req, res) => {
    res.json([
      { id: "1042", item: "Ruskie × 20", status: "delivered" },
      { id: "1057", item: "Z kaczką × 10", status: "cooking" },
    ]);
  });

  return app;
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 2. The API client: token in memory and retry after 401
  • Step 3. AuthProvider and protected routes
  • Step 4. Login and registration forms
  • Step 5. Password reset and returning from social sign-in
  • Step 6. Putting the app together
  • Common mistakes
  • Check yourself
  • What next

Create a free account · Sign in