Log requests with user id in feathersJS

Logging requests in feathersJS is pretty straight forward. Because it is based on express you usually just include morgan and it works like a charm.

But if you want to log which user is requesting a route you need to write a custom token:

const morgan = require('morgan');
const _ = require('lodash');
morgan.token('userId', function (req, res) { 
return _.get(res, 'hook.params.payload._id');
});

There is one thing to mention though: This only works, if you used the verifyToken hook. If you want to be hook independent you could just verify the jwt on your own. But I didn’t want to repeat the code from verifyToken.

There is actually a pitfall within this implementation. If an error gets thrown there is no hook property on the res object. Therefore you need to provide it by writing a custom error handler middleware:

function(error, req, res, next) {
if (error) {
//Make hook accessible for morgan if error occurs
res.hook = error.hook;
}
next(error);
}

This implementation might fail if an error is raised before the token can be verified. But because of lodash’s get function it won’t crash your app, just return undefined which is replaced with a dash by morgan.

You are not restricted to the user id. Maybe you want to add the username:

morgan.token('username', function(req, res) {
return _.get(res, 'hook.params.user.username');
});

But be aware that this requires the populateUser hook to be run.

Hope this was helpful. If there is a better way to log the user or if there is a problem within my implementation let me know in the comments