Why Does My App Forget My Login? Sessions, Cookies, and Tokens — Vibe Coding Lesson 3

Vibe Coding Fundamentals · Season 1 · Lesson 3

Language: English · 한국어

“Logged in” means the server can validate a credential on a request and connect that request to a user—not merely that a name appears on screen. A cookie is browser-managed storage and transport, a session carries login state across requests, and a token is a value the server can validate or look up.

Our question: “Why does my app forget the login on refresh or in another browser?” Let’s extend Lesson 2’s frontend/backend/database model with one more boundary: who gets to decide whether you are signed in?

1. Authentication, sessions, cookies, and tokens do different jobs

  • Authentication checks identity, potentially using a password, passkey, or identity provider. A change in UI is not identity verification.
  • A session keeps login state meaningful across separate HTTP requests. It can use server-stored records or another verifiable-token approach.
  • A cookie is a browser mechanism for storing a value and attaching it to matching requests. A cookie’s presence does not prove authentication.
  • A token is a credential or reference value. An unpredictable session ID is one kind; JWT is one possible format, not a requirement.
  • Authorization decides what an identified user may do. Signing in never automatically grants admin permissions; Lesson 10 covers that distinction.

Decision rule: Ignore the header badge for a moment. Does the server accept a valid protected request (200), reject a request without valid credentials (401), and reject the old credential after logout? Those statuses make the lab clear; a production API may document different response conventions.

2. The mental model: browser carries evidence, server makes the call

  1. Browser → server: A login request arrives. Real apps must verify identity before establishing a signed-in session.
  2. Server: The server can generate a random session ID and store the ID-to-user mapping and expiry.
  3. Server → browser: A Set-Cookie response tells the browser which value to hold, under defined restrictions.
  4. Next request: The browser attaches the matching Cookie. The server checks whether its identifier exists, has expired, or was revoked.
  5. Response → UI: The server returns data or rejects the request. The interface should reflect that result.
WhenBrowserServer
After loginKeeps cookieMaps ID to user
RefreshResends matching cookieValidates session
LogoutReceives clear-cookie instructionRevokes session
ExpiryMay still hold cookieRejects old ID

This flow describes a server-stored session, not every possible authentication design. OWASP’s session guidance treats unpredictability, validation, expiry, and revocation as separate requirements.

3. A small complete local lab: make the server decide

This is a fictional local session exercise for a user called demo. Anyone who clicks “Create demo session” receives one; no real person is authenticated and this is not production login code. No paid API, subscription, database, real credential, or card is required.

  1. Confirm the free Node.js runtime is available with node -v in a terminal; install it from the official site if needed.
  2. Copy the whole code block into session-demo.js; make sure the filename does not end in .txt.
  3. From the directory that contains the file, run node session-demo.js. Leave the terminal open while the server runs.
  4. Open 127.0.0.1:3000/?lang=en in the browser. This is a server running on your own computer. If it fails to open, check the terminal error and whether port 3000 is already used.
  5. Visit /me before creating a session. Return to the page, click “Create demo session,” refresh, and visit /me again.
// Local teaching demo only; this is NOT a real authentication system.
const http = require('node:http');
const { randomBytes } = require('node:crypto');
const sessions = new Map();
const lifeMs = 2 * 60 * 1000;
const words = {
  ko: ['세션 실습', '연습용 세션 만들기', '로그아웃', '서버가 유효한 세션을 찾았어요.', '유효한 세션이 없어요.'],
  en: ['Session lab', 'Create demo session', 'Log out', 'Server found a valid session.', 'No valid session found.']
};
function sessionId(req) {
  const pair = (req.headers.cookie || '').split('; ').find(v => v.startsWith('sid='));
  return pair ? pair.slice(4) : '';
}
http.createServer((req, res) => {
  const [path, query = ''] = req.url.split('?');
  const params = new URLSearchParams(query);
  const lang = params.get('lang') === 'en' ? 'en' : 'ko';
  const w = words[lang];
  const id = sessionId(req);
  const record = sessions.get(id);
  const active = !!record && record.until > Date.now();
  if (record && !active) sessions.delete(id);
  const headers = { 'Cache-Control': 'no-store' };

  if (req.method === 'POST' && path === '/login') {
    const newId = randomBytes(24).toString('hex');
    sessions.set(newId, { userId: 'demo', until: Date.now() + lifeMs });
    res.writeHead(303, { ...headers, Location: '/?lang=' + lang,
      'Set-Cookie': `sid=${newId}; HttpOnly; SameSite=Lax; Path=/` });
    return res.end();
  }
  if (req.method === 'POST' && path === '/logout') {
    sessions.delete(id);
    res.writeHead(303, { ...headers, Location: '/?lang=' + lang,
      'Set-Cookie': 'sid=; Max-Age=0; HttpOnly; SameSite=Lax; Path=/' });
    return res.end();
  }
  if (req.method === 'GET' && path === '/me') {
    res.writeHead(active ? 200 : 401, { ...headers,
      'Content-Type': 'application/json; charset=utf-8' });
    return res.end(JSON.stringify(active ? { userId: record.userId } : { error: 'not_authenticated' }));
  }
  if (req.method === 'GET' && path === '/') {
    res.writeHead(200, { ...headers, 'Content-Type': 'text/html; charset=utf-8' });
    return res.end(`<!doctype html><html lang="${lang}"><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>${w[0]}</title><main style="font:1rem/1.6 system-ui;max-width:34rem;margin:3rem auto;padding:0 1rem">
<h1>${w[0]}</h1><p role="status">${active ? w[3] : w[4]}</p>
<form method="post" action="/login?lang=${lang}"><button>${w[1]}</button></form>
<form method="post" action="/logout?lang=${lang}"><button>${w[2]}</button></form>
<p><a href="/me">/me (JSON)</a></p></main></html>`);
  }
  res.writeHead(404, headers);
  res.end('Not found');
}).listen(3000, '127.0.0.1', () => console.log('Open 127.0.0.1:3000/?lang=ko or ?lang=en'));

What matters: The server’s sessions Map holds the mapping from a random sid to the demo user and expiry. randomBytes(24) creates an unpredictable identifier. The /me route returns 401 without an unexpired record. HttpOnly blocks JavaScript reads of the cookie but does not eliminate XSS. SameSite=Lax helps limit some cross-site requests but is not a complete CSRF defense.

This example only separates the path and query string from req.url; it sends no request to an external server. The cookie carries a random identifier, not a password. Stop the lab with Ctrl+C in the terminal.

4. Success, failure, and expected edge cases

TryExpected resultWhy
/me before login401No valid ID
/me after button200, demoServer accepts cookie
Refresh within two minutesStill signed inCookie sent again
Private window /me401Separate cookie jar
/me after two minutes401Server expiry
/me after logout401Session revoked
Unknown URL path404Route missing, not login

The cookie has no Max-Age, but the server session expires two minutes after creation. Browser cookie lifetime and server session lifetime are different clocks. Restarting the process also clears its Map: an old cookie can remain even though the server no longer accepts its ID.

5. Five failure patterns in AI-generated login

  • ① UI-only sign-in: A component sets isLoggedIn = true but /me still returns 401. A badge change is not authentication.
  • ② Cookie never reaches the server: Check domain, path, HTTPS flags, cross-origin credentials, and server CORS settings. credentials: 'include' does not override SameSite restrictions.
  • ③ Cookie exists but login fails: The record expired, was revoked, vanished on restart, or could not be read. Seeing a cookie in DevTools is not proof of a valid session.
  • ④ Logout clears only the UI: Hiding the profile does not invalidate the server record. Test whether the old credential is rejected.
  • ⑤ Bearer token is exposed to scripts: JavaScript-readable storage increases theft risk under script injection. Consider HttpOnly, production Secure, CSRF protection, and server checks together.

The demo omits Secure for local HTTP, along with identity checks, password handling, CSRF controls, rate limiting, and durable multi-server storage. Real products need HTTPS and a maintained authentication implementation. See MDN’s cookie rules and OWASP’s CSRF guidance.

6. Ask AI for a testable contract, not a login-shaped screen

Weak prompt: “Add login. Show my profile after clicking the button.”

Better prompt: “Inspect the existing stack and auth setup first. Prefer a maintained authentication approach to custom code. Specify how identity is verified by the server; the session, cookie or token boundary; behavior on refresh, expiry, logout, and a private browser; responses without credentials versus insufficient permissions; HTTPS cookie flags and CSRF defenses. Give reproducible checks for each state. A UI-only change does not count as complete. Use fictional identities, never real credentials.”

Before judging the visual result, ask: “Where does the server verify the login state? Will a request without a cookie succeed? Can a logged-out session ID be reused?” If nobody can demonstrate the answers, login has not been verified.

7. Undo and recover

  1. Stop: Use Ctrl+C in the terminal. No session records are written to disk.
  2. Reset: Restart the script. The in-memory session Map is empty; create a new demo session.
  3. Diagnose a misleading UI: Check /me before indiscriminately deleting cookies. If the server returns 401 but the UI says signed in, fix their synchronization.
  4. Production incident: A safe rollback also requires a decision about existing sessions, re-login impact, and potential security response.

8. When not to use this method

A public static portfolio with no per-user protected data may not need login at all. For real accounts, recovery, OAuth, or passkeys, do not grow this lab into your own authentication service. Choose a maintained framework or provider and review its threat model and permission design separately. The small example is enough for learning the boundary.

9. Four questions, with short answers

  1. Q: A cookie remains. Am I logged in? Not necessarily. The server must accept its valid, nonexpired, nonrevoked value.
  2. Q: Does HttpOnly finish security? No. It restricts JavaScript access, but HTTPS, CSRF controls, and server verification still matter.
  3. Q: Is 401 in a private window a bug? No. This lab uses the browser’s separate cookie store.
  4. Q: Does 200 mean I can use admin tools? No. Authentication and authorization are distinct.

10. Continue

Lesson 1 · HTML/CSS/JavaScript distinguished source code from what the browser shows. Lesson 2 · Frontend/Backend/Database introduced state ownership; this lesson made the server responsible for login state. The Wednesday Clinic on data disappearing after refresh and Clinic on SPA refresh 404s diagnose superficially similar symptoms with different causes. Lesson 4 moves to API / JSON / request-response, loading, failures, and retries.

Primary sources


RUDA DIRECTOR · 루다(이루다)

작성자·공개 작업·편집 기준 · 문의·정정 요청

다른 글 보기 · 주제 탐색