{"id":"6b09417f5ce40d447918f2df","slug":"react-auth","title":"Login and registration in React – forms, tokens, protected routes and session refresh","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["authentication","react"],"techs":["typescript","javascript","node"],"tags":["login","registration","refresh-token","httponly-cookie","protected-routes","oauth","password-reset","react-hook-form","zod","react-router"],"level":"intermediate","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":31,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:23.689Z","updatedAt":"2026-11-27T12:59:04.952Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"Login and registration in React step by step – react-hook-form + Zod, access token in memory, refresh token in an httpOnly SameSite cookie, rotation, single-flight refresh and retry after 401, protected routes in React Router 8, password reset without account enumeration, Google sign-in (OAuth) and ","wordCount":6014,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"npm run dev","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Access token in memory, refresh token in an ","marks":[{"type":"bold"}]},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":" cookie.","marks":[{"type":"bold"}]},{"type":"text","text":" JavaScript (including code injected via XSS) can't read the refresh token, and the short-lived access token disappears when the tab closes. A single "},{"type":"text","text":"/auth/refresh","marks":[{"type":"code"}]},{"type":"text","text":" call restores the session after a reload."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"One refresh for many 401s.","marks":[{"type":"bold"}]},{"type":"text","text":" On a 401 the API client refreshes the token once (single-flight) and retries the request. If the refresh fails, the whole app switches to \"signed out\" and the query cache is cleared."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Route protection in React is convenience, not security.","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"RequireAuth","marks":[{"type":"code"}]},{"type":"text","text":" redirects to login and back, but only the server protects data, by checking the token on every request."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you'll build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"An app in Vite + React 19 + React Router 8 + TanStack Query: registration with password validation and a length hint, login that returns users to the page they came from, a protected \"My account\" page with orders, a button that simulates an expired token (so you can watch 401 → refresh → retry in the Network tab), sign-out, password reset with the link printed in the terminal, and a \"Continue with Google\" button with the full redirect flow. The demo API (Express) runs inside the same dev server. The code (20 files) downloads as a ZIP from the icon next to the article."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" React with hooks, react-hook-form and TanStack Query (see the "},{"type":"text","text":"React guide","marks":[{"type":"link","attrs":{"href":"/en/articles/react"}}]},{"type":"text","text":"), HTTP basics (headers, cookies, status codes). We cover the backend only as far as the frontend needs – details in the "},{"type":"text","text":"Authentication","marks":[{"type":"link","attrs":{"href":"/en/topics/authentication"}}]},{"type":"text","text":" topic."}]},{"type":"stats","attrs":{"items":[{"value":"30 s","label":"access token lifetime in the demo","hint":"so you can watch the refresh live"},{"value":"0","label":"tokens in localStorage","hint":"access in memory, refresh in an httpOnly cookie"},{"value":"1","label":"/refresh call","hint":"even when 10 requests get a 401 at once"},{"value":"9","label":"flows tested in a browser","hint":"from registration to Google sign-in"}]}},{"type":"heading","attrs":{"level":2,"id":"where-to-keep-tokens"},"content":[{"type":"text","text":"Where to keep tokens"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Location"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"XSS resistance"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"CSRF"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Session after reload"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Verdict"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"sessionStorage","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"none – any script can read the token"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no risk"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"convenient, but the token leaks on the first XSS"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a plain cookie (no "},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"none"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"needs protection"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the worst of both worlds"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"access in memory + refresh in an ","marks":[{"type":"bold"}]},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":" cookie","marks":[{"type":"bold"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"refresh unreadable by JS, access short-lived"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"SameSite=Strict","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"/api/auth","marks":[{"type":"code"}]},{"type":"text","text":" path"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes, via "},{"type":"text","text":"/refresh","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a good trade-off for SPAs – this guide","marks":[{"type":"bold"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"server session / BFF ("},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":" cookie only)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the token never reaches the browser"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"needs protection"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the most secure, needs a backend-for-frontend"}]}]}]}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant U as User\n  participant R as React (memory)\n  participant A as API\n  U->>R: email + password\n  R->>A: POST /api/auth/login\n  A-->>R: 200 accessToken (JSON) + Set-Cookie refresh_token (httpOnly)\n  R->>A: GET /api/orders (Authorization: Bearer …)\n  A-->>R: 200 orders\n  Note over R,A: after 30 s the access token expires\n  R->>A: GET /api/orders (old token)\n  A-->>R: 401 TOKEN_EXPIRED\n  R->>A: POST /api/auth/refresh (the browser sends the cookie)\n  A-->>R: 200 new accessToken + new cookie (rotation)\n  R->>A: GET /api/orders (new token) – retry\n  A-->>R: 200 orders","caption":"Login, access token expiry and a silent refresh"}},{"type":"heading","attrs":{"level":2,"id":"step-1-project-and-the-demo-api"},"content":[{"type":"text","text":"Step 1. Project and the demo API"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm create vite@latest pierogi-auth -- --template react-ts\ncd pierogi-auth\nnpm install react-router @tanstack/react-query react-hook-form @hookform/resolvers zod\nnpm install -D express cookie-parser @types/express @types/cookie-parser @types/node"}]},{"type":"paragraph","content":[{"type":"text","text":"The Express app is plugged into the Vite dev server as middleware ("},{"type":"text","text":"configureServer","marks":[{"type":"code"}]},{"type":"text","text":"). 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."}]},{"type":"codeGroup","attrs":{"title":"Project configuration"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-auth\",\n  \"private\": true,\n  \"version\": \"0.1.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc --noEmit && vite build\"\n  },\n  \"dependencies\": {\n    \"@hookform/resolvers\": \"^7.0.9\",\n    \"@tanstack/react-query\": \"^5.108.4\",\n    \"react\": \"^19.3.1\",\n    \"react-dom\": \"^19.3.1\",\n    \"react-hook-form\": \"^7.92.0\",\n    \"react-router\": \"^8.5.3\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/cookie-parser\": \"^1.4.10\",\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.0.0\",\n    \"@types/react\": \"^19.3.0\",\n    \"@types/react-dom\": \"^19.3.0\",\n    \"@vitejs/plugin-react\": \"^6.3.0\",\n    \"cookie-parser\": \"^1.4.7\",\n    \"express\": \"^5.3.0\",\n    \"typescript\": \"~7.0.2\",\n    \"vite\": \"^8.4.0\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"es2023\",\n    \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"bundler\",\n    \"types\": [\"vite/client\", \"node\"],\n    \"jsx\": \"react-jsx\",\n    \"noEmit\": true,\n    \"allowImportingTsExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"skipLibCheck\": true,\n    \"noUncheckedIndexedAccess\": true\n  },\n  \"include\": [\"src\", \"server\", \"vite.config.ts\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"vite.config.ts"},"content":[{"type":"text","text":"import react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\nimport { createAuthApi } from \"./server/auth-api.ts\";\n\n// The demo API runs inside the Vite dev server (same origin = simple cookies, no CORS).\n// In production the same Express app runs on its own behind your reverse proxy.\nexport default defineConfig({\n  plugins: [\n    react(),\n    {\n      name: \"auth-api\",\n      configureServer(server) {\n        server.middlewares.use(createAuthApi());\n      },\n    },\n  ],\n});"}]},{"type":"codeBlock","attrs":{"language":"html","filename":"index.html"},"content":[{"type":"text","text":"<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Pierogarnia · Account</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>"}]},{"type":"codeBlock","attrs":{"language":"css","filename":"src/index.css"},"content":[{"type":"text","text":"* { box-sizing: border-box; }\nbody { margin: 0; font-family: system-ui, sans-serif; color: #1f2328; background: #f6f7f9; }\na { color: #c2255c; }\n.shell { max-width: 720px; margin: 0 auto; padding: 16px; }\n.topbar { display: flex; gap: 16px; align-items: center; padding: 12px 0 16px; border-bottom: 1px solid #dee2e6; margin-bottom: 24px; }\n.topbar .spacer { flex: 1; }\n.card { background: #fff; border: 1px solid #dee2e6; border-radius: 12px; padding: 24px; max-width: 420px; margin: 0 auto; display: grid; gap: 14px; }\n.field { display: grid; gap: 4px; }\n.field input { padding: 9px 10px; border: 1px solid #ced4da; border-radius: 8px; font: inherit; }\n.field input[aria-invalid=\"true\"] { border-color: #c92a2a; }\n.password { display: grid; grid-template-columns: 1fr auto; gap: 6px; }\n.error { color: #c92a2a; font-size: 0.875rem; margin: 0; }\n.notice { background: #ebfbee; border: 1px solid #b2f2bb; padding: 10px 12px; border-radius: 8px; margin: 0; }\n.alert { background: #fff5f5; border: 1px solid #ffc9c9; padding: 10px 12px; border-radius: 8px; margin: 0; }\n.muted { color: #6c757d; font-size: 0.875rem; }\nbutton, .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; }\nbutton.secondary, .button.secondary { background: #fff; color: #1f2328; border-color: #ced4da; }\nbutton:disabled { opacity: 0.6; cursor: wait; }\n.divider { display: flex; align-items: center; gap: 8px; color: #6c757d; font-size: 0.875rem; }\n.divider::before, .divider::after { content: \"\"; flex: 1; border-top: 1px solid #dee2e6; }"}]}]},{"type":"paragraph","content":[{"type":"text","text":"The API is production-shaped even though it stores data in memory: passwords hashed with "},{"type":"text","text":"scrypt","marks":[{"type":"code"}]},{"type":"text","text":", the access token in the JSON response, the refresh token in an "},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"SameSite=Strict","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"path=/api/auth","marks":[{"type":"code"}]},{"type":"text","text":" cookie, refresh-token rotation on every refresh, and a password reset that signs the user out on all devices."}]},{"type":"codeGroup","attrs":{"title":"Express: register, login, refresh, password reset, OAuth"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"server/auth-api.ts"},"content":[{"type":"text","text":"// A minimal, in-memory auth API for the tutorial. The flows and cookie flags are production-shaped;\n// the storage (Maps) and the fake Google provider are not.\nimport cookieParser from \"cookie-parser\";\nimport express, { type NextFunction, type Request, type Response } from \"express\";\nimport { randomBytes, randomUUID, scryptSync, timingSafeEqual } from \"node:crypto\";\n\ntype User = { id: string; name: string; email: string; passwordHash: string | null };\ntype Grant = { userId: string; expiresAt: number };\n\nconst usersByEmail = new Map<string, User>();\nconst accessTokens = new Map<string, Grant>();\nconst refreshTokens = new Map<string, Grant>();\nconst resetTokens = new Map<string, Grant>();\n\nconst ACCESS_TTL_MS = 30_000; // deliberately short: watch the silent refresh in the Network tab\nconst REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst REFRESH_COOKIE = \"refresh_token\";\n\nfunction hashPassword(password: string): string {\n  const salt = randomBytes(16);\n  return `${salt.toString(\"hex\")}:${scryptSync(password, salt, 32).toString(\"hex\")}`;\n}\n\nfunction verifyPassword(password: string, stored: string | null): boolean {\n  const [salt, hash] = (stored ?? \"\").split(\":\");\n  if (!salt || !hash) return false;\n  return timingSafeEqual(Buffer.from(hash, \"hex\"), scryptSync(password, Buffer.from(salt, \"hex\"), 32));\n}\n\nconst publicUser = (u: User) => ({ id: u.id, name: u.name, email: u.email });\nconst findUserById = (id: string) => [...usersByEmail.values()].find((u) => u.id === id);\n\n// Access token goes into the JSON body (kept in memory by the SPA);\n// refresh token goes into an httpOnly cookie that JavaScript can't read.\nfunction issueSession(res: Response, user: User) {\n  const accessToken = randomUUID();\n  accessTokens.set(accessToken, { userId: user.id, expiresAt: Date.now() + ACCESS_TTL_MS });\n  const refreshToken = randomBytes(32).toString(\"base64url\");\n  refreshTokens.set(refreshToken, { userId: user.id, expiresAt: Date.now() + REFRESH_TTL_MS });\n  res.cookie(REFRESH_COOKIE, refreshToken, {\n    httpOnly: true,\n    secure: process.env.NODE_ENV === \"production\",\n    sameSite: \"strict\",\n    path: \"/api/auth\", // the cookie is sent only to auth endpoints\n    maxAge: REFRESH_TTL_MS,\n  });\n  return { accessToken, expiresIn: ACCESS_TTL_MS / 1000, user: publicUser(user) };\n}\n\nfunction requireAuth(req: Request, res: Response, next: NextFunction) {\n  const token = req.headers.authorization?.replace(/^Bearer /, \"\");\n  const grant = token ? accessTokens.get(token) : undefined;\n  if (!grant || grant.expiresAt < Date.now()) {\n    res.status(401).json({ code: grant ? \"TOKEN_EXPIRED\" : \"UNAUTHORIZED\", message: \"Authentication required\" });\n    return;\n  }\n  res.locals.userId = grant.userId;\n  next();\n}\n\nexport function createAuthApi() {\n  const app = express();\n  app.use(\"/api\", express.json(), cookieParser());\n\n  app.post(\"/api/auth/register\", (req, res) => {\n    const { name, email, password } = req.body as { name?: string; email?: string; password?: string };\n    if (!name || !email || !password || password.length < 10) {\n      res.status(400).json({ code: \"VALIDATION_FAILED\", message: \"Invalid data\" });\n      return;\n    }\n    const key = email.toLowerCase();\n    if (usersByEmail.has(key)) {\n      res.status(409).json({ code: \"EMAIL_TAKEN\", message: \"An account with this email already exists\" });\n      return;\n    }\n    const user: User = { id: randomUUID(), name, email: key, passwordHash: hashPassword(password) };\n    usersByEmail.set(key, user);\n    res.status(201).json(issueSession(res, user));\n  });\n\n  app.post(\"/api/auth/login\", (req, res) => {\n    const { email, password } = req.body as { email?: string; password?: string };\n    const user = usersByEmail.get((email ?? \"\").toLowerCase());\n    // Same error for \"no such user\" and \"wrong password\" – no account enumeration.\n    if (!user || !verifyPassword(password ?? \"\", user.passwordHash)) {\n      res.status(401).json({ code: \"INVALID_CREDENTIALS\", message: \"Wrong email or password\" });\n      return;\n    }\n    res.json(issueSession(res, user));\n  });\n\n  // Rotation: every refresh invalidates the old refresh token and sets a new cookie.\n  app.post(\"/api/auth/refresh\", (req, res) => {\n    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];\n    const grant = token ? refreshTokens.get(token) : undefined;\n    if (token) refreshTokens.delete(token);\n    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;\n    if (!user) {\n      res.clearCookie(REFRESH_COOKIE, { path: \"/api/auth\" });\n      res.status(401).json({ code: \"NO_SESSION\", message: \"Please sign in\" });\n      return;\n    }\n    res.json(issueSession(res, user));\n  });\n\n  app.post(\"/api/auth/logout\", (req, res) => {\n    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];\n    if (token) refreshTokens.delete(token);\n    res.clearCookie(REFRESH_COOKIE, { path: \"/api/auth\" });\n    res.status(204).end();\n  });\n\n  // Always 204 – the response must not reveal whether the email has an account.\n  app.post(\"/api/auth/forgot-password\", (req, res) => {\n    const user = usersByEmail.get(String(req.body?.email ?? \"\").toLowerCase());\n    if (user) {\n      const token = randomBytes(32).toString(\"base64url\");\n      resetTokens.set(token, { userId: user.id, expiresAt: Date.now() + 30 * 60_000 });\n      console.log(`[mail] Reset link for ${user.email}: http://localhost:5173/reset-password?token=${token}`);\n    }\n    res.status(204).end();\n  });\n\n  app.post(\"/api/auth/reset-password\", (req, res) => {\n    const { token, password } = req.body as { token?: string; password?: string };\n    const grant = token ? resetTokens.get(token) : undefined;\n    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;\n    if (!user || !password || password.length < 10) {\n      res.status(400).json({ code: \"INVALID_TOKEN\", message: \"The link is invalid or has expired\" });\n      return;\n    }\n    resetTokens.delete(token!);\n    user.passwordHash = hashPassword(password);\n    for (const [t, g] of refreshTokens) if (g.userId === user.id) refreshTokens.delete(t); // sign out everywhere\n    res.status(204).end();\n  });\n\n  // Fake \"Sign in with Google\": a real app redirects to the provider with `state` + PKCE here.\n  app.get(\"/api/auth/google\", (_req, res) => {\n    const state = randomBytes(16).toString(\"base64url\");\n    res.cookie(\"oauth_state\", state, { httpOnly: true, sameSite: \"lax\", path: \"/api/auth\", maxAge: 5 * 60_000 });\n    res.redirect(`/api/auth/google/callback?code=demo-code&state=${state}`);\n  });\n\n  app.get(\"/api/auth/google/callback\", (req, res) => {\n    if (!req.query.state || req.query.state !== req.cookies?.oauth_state) {\n      res.redirect(\"/login?error=oauth_state\");\n      return;\n    }\n    res.clearCookie(\"oauth_state\", { path: \"/api/auth\" });\n    // Here the server exchanges `code` for the provider's tokens and reads the verified email.\n    const email = \"halina.demo@gmail.example\";\n    let user = usersByEmail.get(email);\n    if (!user) {\n      user = { id: randomUUID(), name: \"Halina (Google)\", email, passwordHash: null };\n      usersByEmail.set(email, user);\n    }\n    issueSession(res, user); // sets the refresh cookie – no tokens in the URL\n    res.redirect(\"/auth/callback\");\n  });\n\n  app.get(\"/api/me\", requireAuth, (_req, res) => {\n    const user = findUserById(String(res.locals.userId));\n    res.json(user ? publicUser(user) : null);\n  });\n\n  app.get(\"/api/orders\", requireAuth, (_req, res) => {\n    res.json([\n      { id: \"1042\", item: \"Ruskie × 20\", status: \"delivered\" },\n      { id: \"1057\", item: \"Z kaczką × 10\", status: \"cooking\" },\n    ]);\n  });\n\n  return app;\n}"}]}]}]},"toc":[{"id":"where-to-keep-tokens","text":"Where to keep tokens","level":2,"locked":false},{"id":"step-1-project-and-the-demo-api","text":"Step 1. Project and the demo API","level":2,"locked":false},{"id":"step-2-the-api-client-token-in-memory-and-retry-after-401","text":"Step 2. The API client: token in memory and retry after 401","level":2,"locked":true},{"id":"step-3-authprovider-and-protected-routes","text":"Step 3. AuthProvider and protected routes","level":2,"locked":true},{"id":"step-4-login-and-registration-forms","text":"Step 4. Login and registration forms","level":2,"locked":true},{"id":"step-5-password-reset-and-returning-from-social-sign-in","text":"Step 5. Password reset and returning from social sign-in","level":2,"locked":true},{"id":"step-6-putting-the-app-together","text":"Step 6. Putting the app together","level":2,"locked":true},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":true},{"id":"check-yourself","text":"Check yourself","level":2,"locked":true},{"id":"what-next","text":"What next","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":49,"visibleBlocks":14,"resources":[{"id":"6b0857bf3c96f2d34d0b42a9","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/patterns/federated-identity","embedUrl":null,"title":"Federated Identity Pattern","description":"Use the Federated Identity design pattern to delegate authentication to an external identity provider.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["azure","cloud","design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":62,"verifiedAt":"2026-11-26T11:07:49.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857bd3c96f2d34d0b40c4","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/episode-99-shhh-its-a-secret-storing-api-keys/id467641329?i=1000701187746","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id467641329?i=1000701187746","title":"Episode 99. SHHH! It’s a secret! (Storing API Keys / Passwords / tokens!)","description":"Ok, so is time to talk about something secretive! Like API Passwords, Auth tokens, or keys... these are things that we want to have as a Secret within our microservice. And yeah, adding them into your source code is a big no-no Here we cover the dos...","author":"Java Pub House","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts221/v4/ca/24/a7/ca24a7a6-e926-cc14-223a-444cf4127b70/mza_6810655170352985611.png/600x600bb.jpg","durationSec":null,"lang":"en","topics":["microservices"],"techs":["java"],"tags":["podcast","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2022-01-02T05:19:57.000Z","popularity":40,"verifiedAt":"2026-11-26T11:04:06.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857b33c96f2d34d0b36b1","type":"repo","provider":"github","url":"https://github.com/yurisldk/realworld-react-fsd","embedUrl":null,"title":"yurisldk/realworld-react-fsd","description":"A real-world React application built with Feature-Sliced Design, evolving from a modular monolith toward a microfrontend-ready architecture.","author":"yurisldk","thumbnailUrl":"https://opengraph.githubassets.com/1/yurisldk/realworld-react-fsd","durationSec":null,"lang":"en","topics":["modular-monolith","monolith"],"techs":["typescript"],"tags":["feature-sliced","feature-sliced-design","jest","jwt-authentication","modular-monolith","modular-monolith-architecture","software-architecture","orval","react","react-query"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-05-27T20:46:51.000Z","popularity":53,"verifiedAt":"2026-11-26T10:58:41.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.220Z","updatedAt":"2026-11-26T16:00:51.220Z"},{"id":"6b0857c73c96f2d34d0b4926","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=J4ix8Mhi3rs","embedUrl":"https://www.youtube-nocookie.com/embed/J4ix8Mhi3rs","title":"Best Practices for Secure Password Hashing in .NET (Stop Storing Passwords in Plain Text!)","description":"Want to master Clean Architecture? Go here: https://bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: https://bit.ly/3SXlzSt Join a community of 1000+ .NET developers: https://www.patreon.com/milanjovanovic Never store passwords in plain text! In this video, you'll learn the essential…","author":"Milan Jovanović","thumbnailUrl":"https://i.ytimg.com/vi/J4ix8Mhi3rs/hqdefault.jpg","durationSec":null,"lang":"en","topics":["modular-monolith","clean-architecture"],"techs":["dotnet"],"tags":["security","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2024-08-16T11:00:28.000Z","popularity":65,"verifiedAt":"2026-11-26T10:54:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}