0
0
Expressframework~30 mins

Session-based auth with express-session - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use app.get('/dashboard', (req, res) => { ... }). Check req.session.username and respond accordingly.