Write an auth middleware that verifies the JWT and sets req.user. Apply it to single routes, to a router (router.use(auth)), or in app.js. Keep public routes outside the auth middleware.
Express Route Protection With Middlewares
How do I protect routes in Express?
The answer
More FAQs in Express Route Protection With Middlewares
Read from req.cookies.token or req.headers.authorization (Bearer token). Verify with jwt.verify(token, process.env.JWT_SECRET). If valid, set req.user and call next; if not, return 401.
Add a second middleware after auth that checks req.user.role. If not allowed, return 403. Apply with router.use('/admin', auth, requireAdmin). Stack middlewares for layered auth.
In the handler, load the resource and compare its owner to req.user.id. If they do not match, return 403. Do this for any user-specific resource like /posts/:id.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.