-
Notifications
You must be signed in to change notification settings - Fork 193
Middleware for fetching the user information #18
Description
function getUserDataFromReq(req) { return new Promise((resolve, reject) => { jwt.verify(req.cookies.token, jwtSecret, {}, async (err, userData) => { if (err) throw err; resolve(userData); }); }); }
instead of calling this function again and again we can create a middleware and we can add that midleware on each request and there is no need to call this function again and again
Why middleware is better than calling the function repeatedly
❌ Current approach (function call everywhere)
You must call getUserDataFromReq(req) in every route
Easy to forget → security bug
Repeated boilerplate
Poor separation of concerns
✅ Middleware approach (best practice)
JWT verification runs before the controller
Controller receives already-authenticated user
Cleaner, safer, reusable
Scales well as your app grows (especially important for MERN / Nest-style APIs)