Back to Express JS Course
Express JS Course
In Express JS, sessions are used to store user data across requests. They allow you to maintain stateful information between different HTTP requests from the same client.
Lets refactor our code to include sessions.
First, install express-session npm install express-session.
userRouter.mjs
import express from 'express'; import { checkSchema, validationResult } from 'express-validator'; import { createUserValidationSchema } from '../utils/validationSchemas.mjs'; import session from 'express-session'; const router = express.Router(); router.use(session({ secret: 'praveenoruganti', resave: false, saveUninitialized: false, cookie: { maxAge: 900000, // 15 minutes httpOnly: true, } })); const mockUsers = [ { id: 1, name: 'Praveen', designation: 'Technical Architect', city: 'Hyderabad' }, { id: 2, name: 'Prasad', designation: 'Technical Lead', city: 'Bangalore' }, { id: 3, name: 'Anusha', designation: 'Lead Developer', city: 'Chennai' }, { id: 4, name: 'Ravi', designation: 'Developer', city: 'Hyderabad' }, { id: 5, name: 'Kiran', designation: 'Technical Lead', city: 'Hyderabad' }, ]; // Middleware for authentication const authenticate = (req, res, next) => { const apiKey = req.headers['x-api-key']; if ((apiKey && apiKey === '2a5699ae-6e99-4cac-ae55-bb769d9e6090') || req.session.authenticated) { req.session.authenticated = true; next(); } else { res.status(401).send('Unauthorized'); } }; // Route to get all users router.get('/', authenticate, (req, res) => { const isAuthenticated = req.session.authenticated; if (!isAuthenticated) { return res.status(401).send('Unauthorized'); } let filteredUsers = mockUsers; const { name, designation, city } = req.query; if (name) { filteredUsers = filteredUsers.filter(user => user.name.toLowerCase().includes(name.toLowerCase())); } if (designation) { filteredUsers = filteredUsers.filter(user => user.designation.toLowerCase().includes(designation.toLowerCase())); } if (city) { filteredUsers = filteredUsers.filter(user => user.city.toLowerCase().includes(city.toLowerCase())); } res.send({ users: filteredUsers }); }); router.get('/logout', (req, res) => { req.session.destroy(); res.send('Logged out successfully'); }); // Route to get a single user by ID router.get('/:id', (req, res) => { const parsedId = parseInt(req.params.id); if (isNaN(parsedId)) res.status(400).send({ msg: "Bad Request. Invalid ID" }); const findUser = mockUsers.find((user) => user.id === parsedId); if (!findUser) res.status(404).send({ msg: "ID Not Found" }); res.send(findUser); }); // Route to add a new user router.post('/', checkSchema(createUserValidationSchema), (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const newUser = req.body; // Validate the incoming data if (!newUser.name || !newUser.designation || !newUser.city) { return res.status(400).send({ msg: 'Bad Request. Missing required fields' }); } // Assign a new ID to the new user newUser.id = mockUsers.length ? mockUsers[mockUsers.length - 1].id + 1 : 1; // Add the new user to the mockUsers array mockUsers.push(newUser); // Respond with the newly created user res.status(201).send({ user: newUser }); }); // Route to update an existing user router.put('/:id', (req, res) => { const parsedId = parseInt(req.params.id, 10); if (isNaN(parsedId)) { return res.status(400).send({ msg: 'Bad Request. Invalid ID' }); } const findUser = mockUsers.find((user) => user.id === parsedId); if (!findUser) { return res.status(404).send({ msg: 'ID Not Found' }); } const { name, designation, city } = req.body; if (!name || !designation || !city) { return res.status(400).send({ msg: 'Bad Request. Missing required fields' }); } // Update user data findUser.name = name; findUser.designation = designation; findUser.city = city; res.send({ user: findUser }); }); // PATCH endpoint to update user by ID router.patch('/:id', (req, res) => { const id = parseInt(req.params.id); const updatedUser = req.body; // Find the user by ID const userToUpdate = mockUsers.find(user => user.id === id); // If the user is found, update its properties if (userToUpdate) { userToUpdate.name = updatedUser.name; userToUpdate.designation = updatedUser.designation; userToUpdate.city = updatedUser.city; res.status(200).json({ message: 'User updated successfully', user: userToUpdate }); } else { res.status(404).json({ message: 'User not found' }); } }); // Route to delete a user router.delete('/:id', (req, res) => { const userId = parseInt(req.params.id); const userIndex = mockUsers.findIndex(user => user.id === userId); if (userIndex !== -1) { mockUsers.splice(userIndex, 1); res.status(204).send(); // No Content } else { res.status(404).send('User not found'); } }); export default router;
Lets invoke get all users endpoint with api key.

You see a session got created.

Lets invoke get all users endpoint without api key as it was set in the session.
