hagopj13 / hagopj13/node-express-boilerplate
Incorrect http status code 401-Unauthorized returned when MongoDB connection unavailable
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 2.3k
- PR merge metrics
- No merged PRs in 30d
Description
Hey there!
I noticed that MongoDB connection issues will return an incorrect and misleading 401-Unauthorized response. This can happen when the MongoDB connection drops or the MongoDB instance is shutdown or becomes unavailable after the backend app is already started.
The result is that the auth middleware rejects the Promise with an ApiError, however the MongoDB connection error is caught and handled the same way as legitimate auth failures.
With some debugging, see in the `middlewares/auth.js` that regular normal auth failures come on the `info` variable, whereas the Mongoose error comes on the `err` variable as (`MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017`).
EDIT: I see that other auth errors such as using a refresh token instead of auth token will also be on the `err` variable too.
### Problem
The API returns incorrect and misleading "401-Unauthorized" error, which would mislead any client-side apps to thing that the user needs to login again.
### Expectation
1. The API return a 500-Internal Server Error for DB connection errors
2. Log the error so we can see details of the Mongoose/MongoDB or other error so that we can easily determine the cause
### Proposed Solution
In my app I've currently separated the handling of `err`, to log the error and also return a 500 error to the client.
```
if (err && err.stack.includes('MongooseServerSelectionError')) {
logger.error(err);
return reject(new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Internal server error'));
}
if (err || info || !user) {
return reject(new ApiError(httpStatus.UNAUTHORIZED, 'Please authenticate'));
}
```
### Steps to Recreate the Issue
1. Start the server as normal, Mongo up and running
2. Make any successful API call, and receive a 200 or any successful response
3. Break the MongoDB connection, eg, stop or shutdown the Mongo proccess
4. Make the same API call, and after 30 second timeout, you should receive a 401-Unauthorized error
---
I'll submit a PR so you can review further, and I'd be happy to hear alternatives or any thoughts
And I just wanted to say, @hagopj13 , thanks for open sourcing this project! Not only have I gotten great use from it, but I've also learned some new things from it too 🤓
Contributor guide
Assessment
This issue has not been assessed yet.