Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 43 ยท Security and Auth

Sessions and Login

Build login with sessions in Express: session cookies, express-session and Redis stores, password hashing with argon2 and bcrypt, logout and CSRF basics.

HTTP is stateless: every request arrives as a stranger. To let someone log in once and stay logged in, the server has to recognize a returning browser. The classic solution is the session: the server remembers who the user is, and the browser carries only a random, meaningless ticket (the session id) in a cookie.

This lesson walks through the whole login flow: hashing passwords, creating a session at login, protecting routes, logging out, choosing a session store, and the CSRF risk that comes with cookies. The real packages (express-session, argon2, connect-redis) are read-only because npm is not available here. The runnable examples build a small session store and a password check from node:crypto on the stand-in framework from Inside Express.

How a session works

The session dance

Login User sends name and password.
Ticket Server stores data and sends a random id in a cookie.
Cookie The browser returns it on every request.
Recognize Server looks the id up and knows who you are.

The cookie holds an id, not your data.

1 / 2
sequenceDiagram
  participant B as Browser
  participant S as Express server
  participant T as Session store
  B->>S: POST /login (email, password)
  S->>S: check password hash
  S->>T: save session {userId: 7}
  S-->>B: Set-Cookie: sid=abc123; HttpOnly
  B->>S: GET /me<br/>Cookie: sid=abc123
  S->>T: load abc123
  T-->>S: {userId: 7}
  S-->>B: 200 {user}

The browser only ever holds the id; the server keeps the data.

Never store passwords as text

Before any login code, one rule: never store a password, and never store it with a fast hash such as plain SHA-256 or MD5. If your database leaks, attackers will try billions of guesses per second against fast hashes. Use a deliberately slow, salted password hashing function:

  • argon2id is the current recommendation (npm package argon2).
  • scrypt is built into Node (node:crypto) and also good.
  • bcrypt is older but still widely used and acceptable (bcrypt or bcryptjs).

A salt is random data mixed into each hash so two users with the same password get different hashes; these libraries create and store it for you inside the hash string. Real code, read-only:

JavaScript
import argon2 from 'argon2';

const hash = await argon2.hash(password); // salt and settings included
const ok = await argon2.verify(hash, attempt); // true or false

With bcrypt it looks almost the same: await bcrypt.hash(password, 12) and await bcrypt.compare(attempt, hash), where 12 is the cost factor. Raise the cost over time as hardware gets faster.

express-session in real code

express-session is the standard session middleware. A typical setup, read-only:

JavaScript
import express from 'express';
import session from 'express-session';
import { RedisStore } from 'connect-redis';
import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const app = express();
app.set('trust proxy', 1); // needed behind a TLS-terminating proxy

app.use(
  session({
    store: new RedisStore({ client: redis }),
    secret: process.env.SESSION_SECRET, // signs the cookie
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
    },
  }),
);

app.post('/login', express.json(), async (req, res) => {
  const user = await findUserByEmail(req.body.email);
  const valid = user && (await argon2.verify(user.passwordHash, req.body.password));
  if (!valid) {
    return res.status(401).json({ error: 'Invalid email or password' });
  }
  req.session.regenerate((err) => {
    if (err) throw err;
    req.session.userId = user.id;
    res.json({ ok: true });
  });
});

app.post('/logout', (req, res) => {
  req.session.destroy(() => {
    res.clearCookie('connect.sid');
    res.status(204).end();
  });
});

Points worth understanding:

  • secret signs the session cookie so tampering is detected. Keep it out of source control and rotate it with an array of secrets.
  • saveUninitialized: false avoids creating a stored session for every visitor who never logs in.
  • Cookie flags: httpOnly hides the cookie from JavaScript (limits damage from XSS), secure sends it only over HTTPS, sameSite limits cross-site sending (see CSRF below). Cookies and Headers explains each option.
  • regenerate at login issues a fresh session id. Reusing the pre-login id would allow session fixation, where an attacker plants an id and waits for the victim to log in.
  • The error message is the same for "unknown email" and "wrong password" so attackers cannot discover which emails are registered.

Session stores

By default express-session keeps sessions in memory (MemoryStore). That is only for development: it leaks memory, loses everything on restart, and does not work with more than one server process. In production use a shared store such as Redis (fast, supports expiry) or a database-backed store. With Redis any server in a cluster can load any user's session.

Runnable: a session store and login flow

This example implements the same flow with plain pieces. Passwords are hashed with scrypt from node:crypto and a random salt. Sessions live in a Map, the cookie is set with HttpOnly, and the client in start keeps the cookie between calls like a browser does. This is a stand-in: real code should use express-session and a persistent store.

Node.js Login, protected route and logout

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.

The first /me is rejected because there is no cookie. A wrong password gets a 401 and no cookie. A correct login stores a session and sets the cookie; the client then sends it automatically, so /me works. After logout the server deletes the session, so the same cookie (now cleared) no longer opens anything.

Because the cookie travels in a header, you can inspect exactly what the server sets. This is the line to check in browser developer tools too.

Node.js What the Set-Cookie header looks like

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.

The id is random and carries no information, and HttpOnly means page scripts cannot read it. In production you would add Secure as well.

Session idle timeout and rolling sessions

"How long does a user stay logged in?" has three different answers, and security reviews ask which one you chose:

  • Fixed lifetime (also called absolute timeout): the session ends a set time after login, however busy the user is. A bank might choose 8 hours.
  • Idle timeout: the session ends after a period with no activity, for example 15 or 30 minutes. A user who keeps working stays signed in; one who walks away is signed out.
  • Both together: an idle timeout plus an absolute cap, so a session cannot live forever just because someone keeps clicking (or a stolen cookie is kept alive by a script).

With express-session the building blocks are these options (real code, read-only here):

JavaScript
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  rolling: true,                       // re-send the cookie, and so reset its expiry, on EVERY response
  cookie: {
    maxAge: 30 * 60 * 1000,            // 30 minutes, in milliseconds
    httpOnly: true,
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
  },
}));
  • cookie.maxAge is how long the cookie (and the stored session) lasts, in milliseconds.
  • rolling: false (the default) means the cookie is only sent again when the session is created or changed. The browser keeps the expiry date from the first Set-Cookie, so the session behaves like a fixed lifetime counted from login. The server may extend its own copy of the session on each request (req.session.touch() resets it), but the browser deletes the cookie on schedule anyway.
  • rolling: true sends the cookie on every response with a fresh maxAge, so the countdown restarts each time: an idle timeout. Setting maxAge to your idle limit is all it takes.
  • An absolute cap is not built in. Record when the session started and check it yourself:
JavaScript
const ABSOLUTE_MS = 8 * 60 * 60 * 1000;   // 8 hours

function enforceAbsoluteTimeout(req, res, next) {
  if (!req.session.userId) return next();                  // anonymous, nothing to enforce
  req.session.createdAt ??= Date.now();                    // set at login (or regenerate + set there)
  if (Date.now() - req.session.createdAt > ABSOLUTE_MS) {
    return req.session.destroy(() => {
      res.clearCookie('connect.sid');
      res.status(401).json({ error: 'Session expired, please sign in again' });
    });
  }
  next();
}
app.use(enforceAbsoluteTimeout);

req.session.destroy(callback) removes the session from the store; clear the cookie as well so the browser stops sending it. A "log me out" button needs the same two steps. The cookie name connect.sid is the default; rename it with the name option.

Seeing the three policies side by side

Waiting 30 real minutes in a tutorial is not practical, so this example uses a simulated clock (in minutes). The stand-in server follows the same rules: the browser forgets an expired cookie, the cookie is only refreshed when rolling is on, the store has its own expiry, and an optional absolute cap destroys old sessions. It prints what happens to the same user, who clicks every 20 minutes for a while and then goes quiet.

Node.js Fixed lifetime vs idle timeout vs idle plus absolute

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.

Compare the three runs. In A, the user clicked at 20 minutes and was fine, but the 40-minute click found them signed out even though they had been active: the cookie issued at minute 0 expired at minute 30. That surprises users and is the classic mistake of setting maxAge without rolling. In B, every click moved the expiry forward, so the user stayed signed in for 100 minutes and was signed out only when the last gap was longer than 30 minutes (100 to 131). In C, the idle timeout still applies but the absolute cap ended the session after 90 minutes, no matter how active the user was: the click at 100 minutes found it gone.

Pick limits to match the risk. Email or social apps may allow weeks of idle time; banking and admin panels prefer 10 to 20 minutes idle and a few hours absolute. Sensitive actions (changing a password, paying) can ask the user to re-enter their password even inside a valid session. Whatever you choose, tell the user: a friendly "you were signed out because you were inactive" message beats a mysterious redirect. On the client you can also warn a minute before the idle limit.

Two more details. Where the session lives matters: rolling extends the cookie, while the server-side store (Redis, a database) needs a matching TTL, so make sure the store's expiry follows cookie.maxAge. And with JWT access tokens (JWT Authentication) the equivalent of an idle timeout is a short access-token life renewed by a refresh token, which also shortens as the refresh token expires.

Passport and the local strategy

Many apps use Passport, a library that separates "how do I check who this is?" (a strategy) from the rest of your app. The passport-local strategy checks a username and password, and Passport stores the user id in the session. This code is read-only here, because npm packages cannot run on this site:

JavaScript
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
import bcrypt from 'bcrypt';

passport.use(new LocalStrategy(async (username, password, done) => {
  const user = await users.findByName(username);
  if (!user) return done(null, false);
  const ok = await bcrypt.compare(password, user.passwordHash);
  return done(null, ok ? user : false);
}));

passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser(async (id, done) => done(null, await users.findById(id)));

app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }));

serializeUser decides what goes into the session (just the id), deserializeUser rebuilds req.user on later requests. bcrypt.compare hashes the attempt with the stored salt and compares in constant time. Passport is optional: the manual flow above does the same job with less machinery, and Passport shines when you add Google, GitHub or JWT strategies next to the local one.

CSRF: the price of cookies

Browsers attach cookies automatically, even to requests started by another site. If you are logged in at bank.example, a malicious page could make your browser submit a form to bank.example/transfer; your session cookie goes along, and the server sees a legitimate session. That attack is cross-site request forgery (CSRF).

Defenses, usually combined:

  • SameSite=Lax or Strict on the session cookie: the browser does not send it on most cross-site POSTs. This alone stops most CSRF in modern browsers.
  • CSRF tokens: a random value embedded in each form (or sent in a header) that the server checks. Libraries such as csrf-csrf implement the double-submit pattern.
  • Checking Origin/Referer headers for state-changing requests.
  • Never change state with GET.

Token-based APIs that put the credential in an Authorization header are not exposed to CSRF in the same way, but have their own pitfalls; compare them in JWT Authentication. The broader checklist is in Security Best Practices.

Practical advice

  • Rate-limit /login to slow password guessing.
  • Set a session lifetime, and consider both an idle timeout and an absolute one.
  • Regenerate the session id on login and on privilege changes.
  • Destroy the server-side session on logout; clearing only the cookie leaves a valid session behind.
  • Serve everything over HTTPS in production and set secure: true.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the session cookie contain in a server-side session design?

    The cookie holds only an opaque id. The data lives in the session store on the server.
  2. 2. Which is the best choice for storing user passwords?

    Slow, salted password hashes make bulk guessing expensive. Fast hashes and reversible encoding do not.
  3. 3. Why should the login error be the same for an unknown email and a wrong password?

    Different messages reveal which accounts exist, which helps attackers target them.
  4. 4. Why is MemoryStore unsuitable for production?

    Sessions in process memory disappear on restart and cannot be shared across several server processes. Use Redis or a database store.
  5. 5. Which cookie setting is the main modern defense against CSRF?

    SameSite stops the browser from sending the cookie on most cross-site requests. HttpOnly helps against XSS, not CSRF.

Summary

  • A session stores user state on the server; the browser carries only a random id in a cookie.
  • Hash passwords with argon2id, scrypt or bcrypt, never with a fast hash, and never store them as text.
  • express-session with a Redis (or database) store is the production setup; MemoryStore is for development only.
  • Use httpOnly, secure and sameSite cookie flags, regenerate the id at login and destroy the session at logout.
  • Cookies need CSRF protection: SameSite, tokens and no state changes on GET.

Next: JWT Authentication and Authorization.