Bird
Raised Fist0
Expressframework~10 mins

Session-based auth with express-session - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Session-based auth with express-session
Client sends login request
Server checks credentials
Create session and store user info
Send session cookie to client
Client sends requests with cookie
Server reads session from cookie
Allow access
This flow shows how a client logs in, the server creates a session, sends a cookie, and then uses that cookie to authenticate future requests.
Execution Sample
Express
const session = require('express-session');
app.use(session({ secret: 'key', resave: false, saveUninitialized: false }));

app.post('/login', (req, res) => {
  if (req.body.user === 'admin' && req.body.pass === '123') {
    req.session.user = 'admin'; res.send('Logged in');
  } else res.status(401).send('Fail');
});
This code sets up session middleware and a login route that saves user info in the session on success.
Execution Table
StepActionInputSession StateResponse to Client
1Client sends POST /login with user=admin, pass=123{user:'admin', pass:'123'}{}Waiting
2Server checks credentialsuser=admin, pass=123{}Waiting
3Credentials valid, create sessionN/A{user:'admin'}Set-Cookie header sent
4Send response 'Logged in'N/A{user:'admin'}'Logged in' text
5Client sends GET /dashboard with cookieCookie with session ID{user:'admin'}Waiting
6Server reads session from cookieSession ID{user:'admin'}Waiting
7Session valid, allow accessN/A{user:'admin'}Dashboard content
8Client sends GET /dashboard without cookieNo cookie{}Waiting
9Server finds no sessionN/A{}Redirect to /login
10Execution endsN/AN/ANo session, access denied
💡 Execution stops when client has no valid session cookie or after response sent.
Variable Tracker
VariableStartAfter Step 3After Step 6Final
req.sessionundefined{user:'admin'}{user:'admin'}Depends on request
res.headers['Set-Cookie']undefinedSession cookie setSession cookie sentSession cookie present or absent
client.cookieundefinedCookie with session IDCookie with session IDCookie present or absent
Key Moments - 3 Insights
Why does the server send a cookie after login?
The cookie holds the session ID so the server can recognize the client on future requests, as shown in step 3 and 4 of the execution_table.
What happens if the client sends a request without the session cookie?
The server cannot find the session and denies access, redirecting to login as shown in steps 8 and 9.
Is the user info stored on the client or server?
User info is stored on the server inside the session object, while the client only holds a session ID cookie (step 3 and 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the session state after step 3?
Aundefined
B{}
C{user:'admin'}
D{user:'guest'}
💡 Hint
Check the 'Session State' column at step 3 in the execution_table.
At which step does the server send the session cookie to the client?
AStep 2
BStep 3
CStep 5
DStep 7
💡 Hint
Look for 'Set-Cookie header sent' in the 'Response to Client' column.
If the client sends a request without a cookie, what response does the server give?
ARedirect to /login
BDashboard content
CLogged in text
DFail status 401
💡 Hint
See steps 8 and 9 in the execution_table for requests without cookie.
Concept Snapshot
Use express-session middleware to create sessions.
On login, save user info in req.session.
Server sends a cookie with session ID to client.
Client sends cookie on future requests.
Server reads session from cookie to authenticate.
No cookie means no session, access denied.
Full Transcript
This visual execution shows how session-based authentication works with express-session. When a client logs in with correct credentials, the server creates a session object storing user info and sends a cookie with a session ID back to the client. The client includes this cookie in future requests. The server reads the cookie, finds the session, and allows access. If the client sends no cookie or an invalid one, the server denies access and redirects to login. Variables like req.session and response headers change during these steps, showing how state is maintained securely on the server while the client holds only a session ID cookie.

Practice

(1/5)
1. What is the main purpose of using express-session in an Express app?
easy
A. To store user data on the server and keep users logged in across requests
B. To encrypt user passwords before saving to the database
C. To serve static files like images and CSS
D. To handle HTTP request routing

Solution

  1. Step 1: Understand session purpose

    Sessions store user info on the server to remember users between requests.
  2. Step 2: Identify express-session role

    The express-session middleware manages these sessions automatically.
  3. Final Answer:

    To store user data on the server and keep users logged in across requests -> Option A
  4. Quick Check:

    Session-based auth = store user data server-side [OK]
Hint: Sessions keep user info server-side to maintain login [OK]
Common Mistakes:
  • Confusing sessions with password encryption
  • Thinking sessions serve static files
  • Mixing routing with session management
2. Which of the following is the correct way to initialize express-session middleware in an Express app?
easy
A. app.use(expressSession('keyboard cat'))
B. app.session({ secret: 'keyboard cat', resave: true })
C. app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true }))
D. app.sessionMiddleware({ secret: 'keyboard cat' })

Solution

  1. Step 1: Recall express-session syntax

    The middleware is added with app.use(session({ options })).
  2. Step 2: Check options correctness

    Options like secret, resave, and saveUninitialized are standard.
  3. Final Answer:

    app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true })) -> Option C
  4. Quick Check:

    Use app.use(session({...})) with options [OK]
Hint: Use app.use(session({ secret, resave, saveUninitialized })) [OK]
Common Mistakes:
  • Using app.session instead of app.use
  • Passing secret as a string directly
  • Calling non-existent methods like sessionMiddleware
3. Given this Express route using express-session:
app.get('/dashboard', (req, res) => {
  if (req.session.user) {
    res.send(`Welcome, ${req.session.user}!`);
  } else {
    res.status(401).send('Please log in');
  }
});

// Assume req.session.user = 'Alice'
What will the server respond when a logged-in user visits /dashboard?
medium
A. Welcome, Alice!
B. Please log in
C. Error: req.session.user is undefined
D. Redirect to login page

Solution

  1. Step 1: Check session user existence

    The code checks if req.session.user exists; here it is 'Alice'.
  2. Step 2: Determine response

    Since user exists, it sends Welcome, Alice! as response.
  3. Final Answer:

    Welcome, Alice! -> Option A
  4. Quick Check:

    Session user present = welcome message [OK]
Hint: If req.session.user exists, show welcome message [OK]
Common Mistakes:
  • Assuming undefined session user causes error
  • Expecting redirect without code
  • Confusing status 401 with success message
4. Consider this code snippet for session setup:
const session = require('express-session');
app.use(session({
  secret: 'secret123',
  resave: false
}));
What is the likely problem with this setup?
medium
A. Session middleware must be added after routes
B. Missing saveUninitialized option may cause sessions not to save properly
C. resave must be true to save sessions
D. The secret should be a number, not a string

Solution

  1. Step 1: Review required session options

    While secret and resave are set, saveUninitialized is missing.
  2. Step 2: Understand saveUninitialized role

    Without saveUninitialized, some sessions may not be saved, causing unexpected behavior.
  3. Final Answer:

    Missing saveUninitialized option may cause sessions not to save properly -> Option B
  4. Quick Check:

    Always set saveUninitialized option [OK]
Hint: Always include saveUninitialized in session config [OK]
Common Mistakes:
  • Thinking secret must be a number
  • Believing resave must be true
  • Adding middleware after routes
5. You want to protect a route so only logged-in users can access it using express-session. Which middleware function correctly checks the session and redirects unauthorized users to /login?
hard
A. function auth(req, res, next) { if (req.session.user) res.redirect('/login'); else next(); }
B. function auth(req, res) { if (!req.session.user) next(); else res.redirect('/login'); }
C. function auth(req, res, next) { if (req.session.user === undefined) res.send('Access granted'); else next(); }
D. function auth(req, res, next) { if (req.session.user) next(); else res.redirect('/login'); }

Solution

  1. Step 1: Understand middleware signature

    Middleware must have (req, res, next) and call next() to continue.
  2. Step 2: Check session user and redirect logic

    If req.session.user exists, call next() to allow access; otherwise redirect to /login.
  3. Final Answer:

    function auth(req, res, next) { if (req.session.user) next(); else res.redirect('/login'); } -> Option D
  4. Quick Check:

    Session user? next() : redirect [OK]
Hint: Call next() if logged in; else redirect to login [OK]
Common Mistakes:
  • Missing next() call in middleware
  • Reversing condition logic
  • Sending response instead of redirecting