Complete the code to import the express-session middleware.
const session = require('[1]');
The express-session package is imported using require('express-session').
Complete the code to initialize express-session middleware with a secret.
app.use(session({ secret: '[1]', resave: false, saveUninitialized: true }));The secret option is a string used to sign the session ID cookie. Here, 'mySecret' is a valid example.
Fix the error in the code to save a username in the session after login.
app.post('/login', (req, res) => { req.session.[1] = req.body.username; res.send('Logged in'); });
The session property to store the username should be named clearly, here 'username' matches the data stored.
Fill both blanks to check if a user is logged in and redirect accordingly.
app.get('/dashboard', (req, res) => { if (!req.session.[1]) { res.redirect('[2]'); } else { res.send('Welcome to your dashboard'); } });
Check if req.session.username exists to confirm login. If not, redirect to /login page.
Fill all three blanks to destroy the session on logout and redirect to home.
app.post('/logout', (req, res) => { req.session.[1](err => { if (err) { return res.status(500).send('Error logging out'); } res.[2]('[3]'); }); });
Use req.session.destroy() to end the session. Then use res.redirect('/') to send the user to the home page.