This example shows a simple Express app using express-session to handle login, protect a dashboard page, and logout. User info is stored in the session.
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
Step 1: Review required session options
While secret and resave are set, saveUninitialized is missing.
Step 2: Understand saveUninitialized role
Without saveUninitialized, some sessions may not be saved, causing unexpected behavior.
Final Answer:
Missing saveUninitialized option may cause sessions not to save properly -> Option B
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
Step 1: Understand middleware signature
Middleware must have (req, res, next) and call next() to continue.
Step 2: Check session user and redirect logic
If req.session.user exists, call next() to allow access; otherwise redirect to /login.
Final Answer:
function auth(req, res, next) { if (req.session.user) next(); else res.redirect('/login'); } -> Option D
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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.