fastify / help

Need help with Fastify? File an Issue here.
https://www.fastify.io/
65 stars 8 forks source link

Access to `request.session` in fastify logger #787

Closed foxadb closed 1 year ago

foxadb commented 1 year ago

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 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.

Version used

Thanks for you help!

climba03003 commented 1 year ago

I am afraid you need to explicitly log it yourself. When the log is printed, no hook is actually executed and that's why the session is always null.