How do you write authentication middleware in Express?
Model answer
Read the token from the Authorization header (Bearer) or a cookie, verify it with jwt.verify and your secret, load or attach the user to req.user, and call next(). On failure return 401. Then add authorisation checks, like role checks and ownership checks, for each protected route.
Learn this topic
Login with JWT: Sign In, Issue a Token and Avoid Timing Leaks in the course MERN Stack Full Course: MongoDB, Express, React and Node.js.
Sign in to add your own answer.