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
Session-based auth with express-session
📖 Scenario: You are building a simple web server that lets users log in and keeps them logged in using sessions. This means the server remembers who the user is between page visits.We will use the express-session library to handle sessions in Express.
🎯 Goal: Create an Express server that uses express-session to store user login state. You will set up session middleware, create a login route that saves the username in the session, and a protected route that only logged-in users can access.
📋 What You'll Learn
Create an Express app with express-session middleware
Set a session secret in the configuration
Create a /login POST route that saves req.body.username in req.session.username
Create a /dashboard GET route that checks if req.session.username exists and responds accordingly
💡 Why This Matters
🌍 Real World
Session-based authentication is common in websites to remember logged-in users without asking for credentials every time.
💼 Career
Understanding session management is essential for backend developers working with user authentication and stateful web applications.
Progress0 / 4 steps
1
Setup Express app and import express-session
Create an Express app by requiring express and express-session. Then call express() and store it in a variable called app.
Express
Hint
Use require('express') and require('express-session') to import the modules. Then create the app with express().
2
Configure express-session middleware
Add the express-session middleware to app using app.use(). Use a session secret string 'mysecret' in the configuration object.
Express
Hint
Use app.use(session({ secret: 'mysecret', resave: false, saveUninitialized: true })) to add session support.
3
Create /login POST route to save username in session
Add a POST route /login to app. Inside the route handler, save req.body.username to req.session.username. Use express.json() middleware to parse JSON bodies.
Express
Hint
Use app.post('/login', (req, res) => { ... }). Inside, assign req.session.username = req.body.username and send a response.
4
Create /dashboard GET route to check session and respond
Add a GET route /dashboard to app. Inside the handler, check if req.session.username exists. If yes, respond with Welcome, {username}. Otherwise, respond with Access denied.
Express
Hint
Use app.get('/dashboard', (req, res) => { ... }). Check req.session.username and respond accordingly.
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
Step 1: Understand session purpose
Sessions store user info on the server to remember users between requests.
Step 2: Identify express-session role
The express-session middleware manages these sessions automatically.
Final Answer:
To store user data on the server and keep users logged in across requests -> Option A
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
Step 1: Recall express-session syntax
The middleware is added with app.use(session({ options })).
Step 2: Check options correctness
Options like secret, resave, and saveUninitialized are standard.
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]