EthicsComputerCourses
Join training +91 90532 10052

Authentication with Sessions & JWT

PERN Stack · Lesson 8 of 20 Intermediate 13 min read Updated

By the end of this lesson KharchaBook will have accounts: people register, log in and log out, and every expense belongs to one user, so Priya never sees Rohan's spending. You will hash passwords with argon2, keep a signed JSON Web Token in an HttpOnly cookie, protect routes with requireAuth, and filter every query by user.

What you should know first: Querying PostgreSQL with node-postgres, whose data layer we extend here. The building blocks have their own lessons: Password Hashing & Sessions, JWT Authentication and Authorisation: Roles & Ownership. Versions used: argon2 0.45.2, jsonwebtoken 9.0.3 and cookie-parser 1.4.7. Every output below comes from running this code.

Two words first

Authentication answers "who are you?". Authorisation answers "what may you do?". Logging in is authentication. Showing Priya only her own expenses is authorisation. This lesson does both.

HTTP has no memory, so after login the browser must send proof with every request. Two common kinds:

Server-side sessionJWT (our choice)
What the browser holdsA random session idA signed token with the user id inside
What the server keepsA sessions table or store, looked up on every requestOnly the signing secret
Log out everywhere at onceEasy: delete the session rowsHard: a token stays valid until it expires
Extra moving partsA session store (such as connect-pg-simple)None

Think of a cinema in Pune. A session is like a cloakroom token: the number means nothing alone, and the counter looks it up in its register. A JWT is like a ticket printed with your seat and a tamper-proof hologram: the usher checks the hologram and does not need any register.

We use a JWT because it needs no extra table or store, and keep it in a cookie, because where the proof lives matters most.

Many tutorials keep the token in localStorage. The problem is XSS (cross-site scripting): if an attacker ever runs a script on your page, that script can read localStorage and steal the token. A cookie with these flags is much safer:

  • HttpOnly: JavaScript cannot read the cookie at all, not even your own code.
  • Secure: the browser sends it only over HTTPS. Browsers such as Chrome treat http://localhost as secure, so development still works.
  • SameSite=Strict: the browser does not send it with requests started by other websites. This blocks CSRF (cross-site request forgery), where another site tricks your browser into calling our API.
  • Path=/api: the cookie goes only to API routes.

Our API also accepts only JSON bodies, which another website cannot send without a CORS check that our allow-list refuses.

Step 1: the users migration

Add server/db/migrations/002_create_users.sql. It creates users and gives every expense an owner:

SQL
-- 002_create_users.sql: accounts, and an owner for every expense.
BEGIN;

CREATE TABLE users (
  id            integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email         text NOT NULL UNIQUE CHECK (email = lower(email) AND length(email) <= 254),
  name          text NOT NULL CHECK (length(name) BETWEEN 1 AND 60),
  password_hash text NOT NULL,
  created_at    timestamptz NOT NULL DEFAULT now()
);

-- KharchaBook is not live yet, so we remove the sample expenses (they have no owner).
-- The updated seed.sql adds them back for a demo user.
DELETE FROM expenses;

ALTER TABLE expenses
  ADD COLUMN user_id integer NOT NULL REFERENCES users (id) ON DELETE CASCADE;

-- Every list is now "this user's expenses, newest first".
DROP INDEX expenses_spent_on_idx;
CREATE INDEX expenses_user_spent_on_idx ON expenses (user_id, spent_on DESC, id DESC);

COMMIT;

Run it as the owner role, exactly like 001:

Terminal
psql "postgres://kharcha_owner@localhost:5432/kharchabook" -f db/migrations/002_create_users.sql
Output
BEGIN
CREATE TABLE
DELETE 8
ALTER TABLE
DROP INDEX
CREATE INDEX
COMMIT

Your DELETE count depends on how many test rows you had. Emails are stored in lowercase (the CHECK enforces it), so Priya@Example.in and priya@example.in are one account, and UNIQUE creates a constraint named users_email_key. ON DELETE CASCADE removes a user's expenses with the user. The new index starts with user_id, because every list now filters by user first.

kharcha_app can already use users, thanks to the default privileges from the schema lesson. The seed file now adds a demo user, priya@example.in with the password pune-ghar-2026, and gives her the five sample expenses. The hash comes from the script in Step 2:

SQL
INSERT INTO categories (name) VALUES
  ('Groceries'), ('Rent'), ('Utilities'), ('Transport'),
  ('Education'), ('Health'), ('Eating out'), ('Other')
ON CONFLICT (name) DO NOTHING;

-- Demo login: priya@example.in / pune-ghar-2026 (development only)
INSERT INTO users (email, name, password_hash) VALUES
  ('priya@example.in', 'Priya',
   '$argon2id$v=19$m=65536,t=3,p=4$78N17UaUtoqTO17S2JUWOg$zF5PJIljyN947iIpktlMH2edAWt4MfITt/0vQ7sGz1w')
ON CONFLICT (email) DO NOTHING;

INSERT INTO expenses (user_id, amount, category_id, spent_on, note)
SELECT u.id, v.amount, v.category_id, v.spent_on, v.note
FROM users u
CROSS JOIN (VALUES
  (18000.00, 2, date '2026-11-01', 'November rent, Kothrud flat'),
  (2340.50, 1, date '2026-11-02', 'DMart monthly ration'),
  (120.00, 4, date '2026-11-03', 'Auto to Shivajinagar'),
  (1460.00, 3, date '2026-11-05', 'MSEDCL electricity bill'),
  (650.00, 7, date '2026-11-08', 'Misal pav, family outing')
) AS v (amount, category_id, spent_on, note)
WHERE u.email = 'priya@example.in';

After the migration it printed INSERT 0 0 (ON CONFLICT skipped the existing categories), INSERT 0 1 and INSERT 0 5.

Step 2: hash passwords with argon2

Install the three new packages:

Terminal
npm install argon2 jsonwebtoken cookie-parser -w server
Output
added 28 packages, and audited 164 packages in 12s

43 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

A hash is a one-way fingerprint: easy to compute from the password, practically impossible to turn back. argon2 is a password hashing algorithm designed to be slow and to need a lot of memory, so an attacker who steals the table cannot try billions of guesses quickly. Here is server/scripts/hash.js:

JavaScript
// Prints an argon2 hash for a password given on the command line.
import argon2 from "argon2";

const hash = await argon2.hash(process.argv[2]);
console.log(hash);
console.log(await argon2.verify(hash, process.argv[2]), await argon2.verify(hash, "wrong-password"));
Output
$argon2id$v=19$m=65536,t=3,p=4$78N17UaUtoqTO17S2JUWOg$zF5PJIljyN947iIpktlMH2edAWt4MfITt/0vQ7sGz1w
true false

Read the hash from left to right: the variant (argon2id), the settings (64 MiB of memory, 3 passes, 4 lanes; these are the package defaults), a random salt, and the result. The salt means two people with the same password get different hashes. If you must use bcrypt in an older project, remember that it ignores everything after 72 bytes of the password.

Anyone with the signing secret can make valid tokens for any user, so it lives only in server/.env. Generate a long random value:

Terminal
node -e "console.log(require('node:crypto').randomBytes(32).toString('base64url'))"

Put the printed value in server/.env as JWT_SECRET=..., and a placeholder in .env.example. Then teach config.js to refuse short secrets:

JavaScript
function secret(name) {
  const value = required(name);
  if (value.length < 32) {
    throw new Error(`${name} must be at least 32 characters long.`);
  }
  return value;
}

export const config = {
  port: Number(process.env.PORT ?? 4000),
  clientOrigin: required("CLIENT_ORIGIN"),
  databaseUrl: required("DATABASE_URL"),
  jwtSecret: secret("JWT_SECRET"),
};

Now server/src/middleware/auth.js, which owns everything about the token:

JavaScript
import jwt from "jsonwebtoken";
import { config } from "../config.js";
import { HttpError } from "./errors.js";

const COOKIE = "kb_token";
const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
const cookieOptions = { httpOnly: true, secure: true, sameSite: "strict", path: "/api" };

// Signs a token for this user and stores it in an HttpOnly cookie.
export function setAuthCookie(res, userId) {
  const token = jwt.sign({ sub: String(userId) }, config.jwtSecret, {
    algorithm: "HS256",
    expiresIn: "7d",
  });
  res.cookie(COOKIE, token, { ...cookieOptions, maxAge: WEEK_MS });
}

export function clearAuthCookie(res) {
  res.clearCookie(COOKIE, cookieOptions);
}

// Lets the request through only with a valid token; sets req.userId.
export function requireAuth(req, res, next) {
  try {
    const payload = jwt.verify(req.cookies[COOKIE], config.jwtSecret, { algorithms: ["HS256"] });
    req.userId = Number(payload.sub);
  } catch {
    throw new HttpError(401, "UNAUTHENTICATED", "Please log in to continue.");
  }
  next();
}

The token carries only sub (subject, the user id), plus the issue and expiry times that jsonwebtoken adds. algorithms: ["HS256"] tells verify to accept only the algorithm we sign with. A missing, expired or edited token makes verify throw, and Express 5 turns our thrown HttpError into a 401 response. next() sits outside the try, so errors from later code are not mistaken for login problems.

Step 4: register, log in, log out

server/src/routes/auth.js has four routes. New helpers: src/data/users.js (createUser, findUserById, and findLogin(email), the only one that returns the hash) and src/validation/auth.js, which lowercases emails and asks for 12 to 128 characters on register. The upper limit stops someone sending a huge "password" to tire out the hashing.

JavaScript
// Used when the email is unknown, so a wrong email takes as long as a wrong password.
const DUMMY_HASH = await argon2.hash("no-such-user-placeholder");

router.post("/register", async (req, res) => {
  const { value, errors } = validateRegister(req.body);
  check(errors);
  const passwordHash = await argon2.hash(value.password);
  const user = await users.createUser({ email: value.email, name: value.name, passwordHash });
  setAuthCookie(res, user.id);
  res.status(201).location("/api/auth/me").json({ data: user });
});

router.post("/login", async (req, res) => {
  const { value, errors } = validateLogin(req.body);
  check(errors);
  const found = await users.findLogin(value.email);
  const ok = await argon2.verify(found?.passwordHash ?? DUMMY_HASH, value.password);
  if (!found || !ok) {
    throw new HttpError(401, "UNAUTHENTICATED", "Email or password is wrong.");
  }
  setAuthCookie(res, found.user.id);
  res.json({ data: found.user });
});

router.post("/logout", (req, res) => {
  clearAuthCookie(res);
  res.status(204).end();
});

router.get("/me", requireAuth, async (req, res) => {
  const user = await users.findUserById(req.userId);
  if (!user) {
    throw new HttpError(401, "UNAUTHENTICATED", "Please log in to continue.");
  }
  res.json({ data: user });
});

check(errors) throws the usual VALIDATION_FAILED error. Login gives one message for both a wrong email and a wrong password, and runs argon2.verify against DUMMY_HASH for unknown emails, so neither the words nor the timing reveal who has an account. Register lets the UNIQUE constraint catch duplicates, and we add users_email_key: ["email", "An account with this email already exists."] to the constraint map in errors.js.

Step 5: protect the expenses

Three changes in app.js: read cookies, allow credentials in CORS, and put requireAuth in front of the expenses router:

JavaScript
app.use(helmet());
app.use(cors({ origin: config.clientOrigin, credentials: true }));
app.use(express.json({ limit: "10kb" }));
app.use(cookieParser());

app.get("/api/health", (req, res) => {
  res.json({ status: "ok" });
});
app.use("/api/auth", authRouter);
app.use("/api/categories", categoriesRouter);
app.use("/api/expenses", requireAuth, expensesRouter);

credentials: true lets the browser send cookies when the client is on another origin. It is safe only because origin is our one-site allow-list. Categories stay public: they are the same for everyone.

Then every data function takes the user id first, and every query filters by it. In src/data/expenses.js:

JavaScript
export async function getExpense(userId, id) {
  const { rows } = await query(
    `SELECT ${FIELDS}
     FROM expenses e JOIN categories c ON c.id = e.category_id
     WHERE e.user_id = $1 AND e.id = $2`,
    [userId, id],
  );
  return rows[0] ? toExpense(rows[0]) : null;
}

export async function deleteExpense(userId, id) {
  const { rowCount } = await query(
    "DELETE FROM expenses WHERE user_id = $1 AND id = $2",
    [userId, id],
  );
  return rowCount === 1;
}

The other functions change the same way: user_id = $1 in the WHERE, or as the first inserted value. The routes pass req.userId, for example expenses.getExpense(req.userId, parseId(req.params.id)). The user id always comes from the verified token, never from the request body or URL.

Step 6: try it with curl

curl can keep cookies in a file: -c saves them, -b sends them. Without a cookie, the expenses are closed:

Terminal
curl -i http://localhost:4000/api/expenses
Output
HTTP/1.1 401 Unauthorized
{"error":{"code":"UNAUTHENTICATED","message":"Please log in to continue."}}

Log in as Priya, with capital letters in the email on purpose:

Terminal
curl -i -c priya.txt -X POST http://localhost:4000/api/auth/login -H "Content-Type: application/json" -d '{"email": "Priya@Example.in", "password": "pune-ghar-2026"}'
Output
HTTP/1.1 200 OK
Set-Cookie: kb_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaWF0IjoxNzk0ODA5OTk0LCJleHAiOjE3OTU0MTQ3OTR9.ftHAUlditAVYPJuhgkfpNkUW20-s6_IjwiAahuGucuQ; Max-Age=604800; Path=/api; Expires=Mon, 23 Nov 2026 06:19:54 GMT; HttpOnly; Secure; SameSite=Strict
{"data":{"id":1,"email":"priya@example.in","name":"Priya"}}

With -b priya.txt, GET /api/expenses now returns Priya's five expenses. The other cases, each with its real response:

RequestStatusResponse body
Login with a wrong password401{"error":{"code":"UNAUTHENTICATED","message":"Email or password is wrong."}}
Register rohan@example.in201{"data":{"id":2,"email":"rohan@example.in","name":"Rohan"}} plus his own cookie
Rohan: GET /api/expenses/20 (Priya's)404{"error":{"code":"NOT_FOUND","message":"Expense 20 was not found."}}
Rohan: DELETE /api/expenses/20404the same 404; the row is untouched
Rohan: GET /api/expenses200{"data":[]}
Register rohan@example.in again400VALIDATION_FAILED with "email":"An account with this email already exists."
Priya's token with sub edited to "2"401UNAUTHENTICATED: the signature no longer matches
POST /api/auth/logout204Set-Cookie: kb_token=; ... Expires=Thu, 01 Jan 1970 ...

Rohan gets 404, not 403, for Priya's expense: for him it does not exist, so he cannot even learn which ids are in use. Reading another user's record by changing an id in the URL is called IDOR (insecure direct object reference), one of the most common API bugs. Filtering by user_id in SQL closes it.

Anyone can read a JWT

A JWT has three parts separated by dots: a header, a payload and a signature. The first two are only base64url-encoded, not encrypted. This example decodes Priya's real token from the login above, with no secret at all:

React JSXOpen in editor
import { createRoot } from "react-dom/client";

// The kb_token value from the curl login above
const token =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaWF0IjoxNzk0ODA5OTk0LCJleHAiOjE3OTU0MTQ3OTR9.ftHAUlditAVYPJuhgkfpNkUW20-s6_IjwiAahuGucuQ";

function decodePart(part) {
  const base64 = part.replaceAll("-", "+").replaceAll("_", "/");
  return JSON.parse(atob(base64));
}

function TokenViewer() {
  const [header, payload] = token.split(".").map((part, i) => (i < 2 ? decodePart(part) : part));
  const expires = new Date(payload.exp * 1000).toISOString();
  console.log("header:", JSON.stringify(header));
  console.log("payload:", JSON.stringify(payload));
  console.log("expires (UTC):", expires);
  return (
    <dl>
      <dt>Algorithm</dt><dd>{header.alg}</dd>
      <dt>User id (sub)</dt><dd>{payload.sub}</dd>
      <dt>Expires</dt><dd>{expires}</dd>
    </dl>
  );
}

createRoot(document.getElementById("root")).render(<TokenViewer />);
Output
header: {"alg":"HS256","typ":"JWT"}
payload: {"sub":"1","iat":1794809994,"exp":1795414794}
expires (UTC): 2026-11-23T06:19:54.000Z

Reading is easy; changing is not. Edit sub to "2" and the signature no longer matches, which is the 401 in the table above. So never put anything private in a token. And because our cookie is HttpOnly, a script on the page never gets the token string at all; in localStorage it would be one getItem() call away.

Common mistakes

  • Storing the token in localStorage. Any XSS bug can read it. Use an HttpOnly cookie.
  • Trusting a user id from the body or URL. Take it only from the verified token, and filter every query by it.
  • A short or committed JWT_SECRET. Use 32 or more random bytes, keep it in .env, and rotate it if it leaks (every token then becomes invalid).
  • No limit on login attempts. Add rate limiting before going live; see Security Checklist for PERN.

Interview questions

1. Where should a browser app keep a JWT, and why?

In an HttpOnly, Secure, SameSite cookie. JavaScript cannot read an HttpOnly cookie, so an XSS bug cannot steal it, and SameSite stops other sites from sending it with forged requests. localStorage is readable by any script on the page.

2. What is the main drawback of JWTs compared with server-side sessions?

A JWT is valid until it expires, because the server keeps no record of it. Logging out only deletes the cookie from that browser. To revoke tokens early you need short expiry times, a token version stored per user, or a deny-list, which brings back some server state.

3. Why use argon2 or bcrypt instead of SHA-256 for passwords?

SHA-256 is designed to be fast, so attackers can test billions of guesses per second. argon2 and bcrypt are deliberately slow and salted, and argon2id also needs a lot of memory, which makes large-scale guessing on GPUs expensive.

4. How do you stop one user reading another user's data?

Take the user id from the verified token and include it in every query, for example WHERE user_id = $1 AND id = $2. Return 404 when no row matches. Never accept an owner id from the client.

Key points

  • Migration 002 adds users (lowercase unique email, password_hash) and a required user_id on expenses.
  • Hash passwords with argon2.hash() (argon2id by default) and check them with argon2.verify().
  • After login, the server signs a JWT with only the user id and sets it in an HttpOnly, Secure, SameSite=Strict cookie.
  • requireAuth verifies the token, allows only HS256, and sets req.userId; failures become a 401 UNAUTHENTICATED error.
  • Every expense query filters by user_id; other users' records answer 404.
  • Login uses one error message and a dummy hash, so it reveals nothing about which emails exist.

Exercise

Add PUT /api/auth/password for logged-in users. The body has currentPassword and newPassword. Check the current password with argon2, apply the same 12 to 128 character rule to the new one, save the new hash, and answer 204. A wrong current password should give a 400 VALIDATION_FAILED error with a message under currentPassword. Add the data function to src/data/users.js.

Show solution
JavaScript
// src/data/users.js
export async function getPasswordHash(id) {
  const { rows } = await query("SELECT password_hash FROM users WHERE id = $1", [id]);
  return rows[0]?.password_hash ?? null;
}

export async function setPasswordHash(id, passwordHash) {
  await query("UPDATE users SET password_hash = $2 WHERE id = $1", [id, passwordHash]);
}

// src/routes/auth.js
router.put("/password", requireAuth, async (req, res) => {
  const current = typeof req.body?.currentPassword === "string" ? req.body.currentPassword : "";
  const next = typeof req.body?.newPassword === "string" ? req.body.newPassword : "";
  const errors = {};
  if (next.length < 12 || next.length > 128) {
    errors.newPassword = "Use a password of 12 to 128 characters.";
  }
  const hash = await users.getPasswordHash(req.userId);
  if (!hash || !(await argon2.verify(hash, current))) {
    errors.currentPassword = "Your current password is wrong.";
  }
  check(errors);
  await users.setPasswordHash(req.userId, await argon2.hash(next));
  res.status(204).end();
});

Both checks run before anything is saved, so the form can show both messages at once. Because JWTs are not stored, other devices stay logged in until their tokens expire; a token_version column checked in requireAuth would log them out too.

Quick Quiz

1. What does the HttpOnly flag on the kb_token cookie do?

2. Rohan requests GET /api/expenses/20, which belongs to Priya. What should the API answer?

3. Why does login call argon2.verify even when the email is unknown?

4. What should the JWT payload contain in KharchaBook?

Learn PERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call