I would like to access to the request.session object inside the logger.\
For my need, it's especially useful to log which user is running each http request.
However it seems that request.session is always null when serializing the request inside the logger.
See bellow a code snippet as example:
import FastifySecureSession from '@fastify/secure-session';
import Fastify from 'fastify';
import pino from 'pino';
const logger = pino({
serializers: {
req(request) {
return {
// method and url are properly defined 👍
method: request.method,
url: request.url,
// username will be undefined because request.session is null 👎
username: request.session?.get('username')
};
}
}
});
const fastify = Fastify({ logger });
fastify.register(FastifySecureSession, {
cookieName: 'my-session-cookie',
key: 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
cookie: {
path: '/'
}
});
fastify.post('/', (request, reply) => {
request.session.set('username', 'johncena');
reply.status(204).send();
});
fastify.get('/', (request, reply) => {
// username is 'johncena' if we call POST before, undefined otherwise
const username = request.session.get('username');
reply.send(`Hello ${username}`);
});
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
});
What was the result you received?
request.session is always null in the logger.
What did you expect?
request.session is not null within the logger, and the username property is defined in the logs.
Hello 👋
I'm using @fastify/secure-session along with fastify and pino as logger for http requests.
I would like to access to the
request.session
object inside the logger.\ For my need, it's especially useful to log which user is running each http request.However it seems that
request.session
is alwaysnull
when serializing the request inside the logger.See bellow a code snippet as example:
What was the result you received?
request.session
is alwaysnull
in the logger.What did you expect?
request.session
is notnull
within the logger, and theusername
property is defined in the logs.Version used
Thanks for you help!