Bird
Raised Fist0
Expressframework~20 mins

Session-based auth with express-session - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Session Auth Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens after a successful login with express-session?
Consider this Express route using express-session for login:
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  if (username === 'user' && password === 'pass') {
    req.session.user = username;
    res.send('Logged in');
  } else {
    res.status(401).send('Unauthorized');
  }
});

What will be stored in the session after a successful login?
ANothing is saved in the session; session remains empty.
BAn object { username: 'user', password: 'pass' } is saved in req.session.user.
CThe username string 'user' is saved in req.session.user.
DThe password string 'pass' is saved in req.session.password.
Attempts:
2 left
💡 Hint
Look at what property of req.session is assigned after login.
state_output
intermediate
2:00remaining
What is the session state after logout?
Given this logout route:
app.post('/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) {
      return res.status(500).send('Error');
    }
    res.send('Logged out');
  });
});

What is the state of req.session after logout completes successfully?
Areq.session is undefined or null after destroy.
Breq.session still contains previous user data.
Creq.session is an empty object {}.
Dreq.session contains a flag loggedOut: true.
Attempts:
2 left
💡 Hint
What does req.session.destroy() do to the session?
📝 Syntax
advanced
2:00remaining
Which code correctly configures express-session middleware?
Choose the correct way to set up express-session middleware with a secret and resave option:
Aapp.use(session({ secret: 'mysecret', resave: false, saveUninitialized: true }));
Bapp.use(session({ secret: 'mysecret', resave: false, saveUninitialized }));
Capp.use(session({ secret: 'mysecret', resave: 'false', saveUninitialized: true }));
Dapp.use(session = { secret: 'mysecret', resave: false, saveUninitialized: true });
Attempts:
2 left
💡 Hint
Check the syntax for calling middleware and option types.
🔧 Debug
advanced
2:00remaining
Why does session data not persist between requests?
A developer uses express-session but notices session data resets on every request. Which mistake causes this?
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: false
}));

app.get('/set', (req, res) => {
  req.session.value = 42;
  res.send('Value set');
});

app.get('/get', (req, res) => {
  res.send('Value: ' + req.session.value);
});
AsaveUninitialized is false, so session never created.
Bresave is false, so session never saves changes.
CThe app is missing cookie-parser middleware before session.
DThe client does not accept cookies, so session ID is lost.
Attempts:
2 left
💡 Hint
Think about how sessions track users across requests.
🧠 Conceptual
expert
2:00remaining
What is the main security risk if express-session secret is exposed?
If the secret used in express-session middleware is leaked, what is the biggest risk?
AAttackers can read all session data stored on the server.
BAttackers can forge session cookies and impersonate users.
CAttackers can delete sessions from the session store remotely.
DAttackers can cause the server to crash by sending malformed cookies.
Attempts:
2 left
💡 Hint
Think about what the secret is used for in cookie signing.

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