- Full-Stack React Projects
- Shama Hoque
- 154字
- 2021-06-25 21:45:10
Auth error handling for express-jwt
To handle the auth-related errors thrown by express-jwt when it tries to validate JWT tokens in incoming requests, we need to add the following error-catching code to the Express app configuration in mern-skeleton/server/express.js, near the end of the code, after the routes are mounted and before the app is exported:
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).json({"error" : err.name + ": " + err.message})
}
})
express-jwt throws an error named UnauthorizedError when the token cannot be validated for some reason. We catch this error here to return a 401 status back to the requesting client.
With user auth implemented for protecting routes, we have covered all the desired features of a working backend for the skeleton MERN application. In the next section, we will look at how we can check if this standalone backend is functioning as desired without implementing a frontend.