session icon indicating copy to clipboard operation
session copied to clipboard

`Session#regenerate` does not call `SessionStore#destroy`

Open SpraxDev opened this issue 10 months ago • 1 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.26.2

Plugin version

10.7.0

Node.js version

20.11.1

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

5.15.150-1-MANJARO

Description

I am trying to regenerate a session in one of my routes to make sure whatever data is in there is reset and I would prefer to also get a new session id as I am essentially restarting the session.

But as far as I can see there is no way for me, without manually interacting with the SessionStore myself, to delete the old session id.

#regenerate only generates a new session for me and stores it.

Steps to Reproduce

Something like:

this.fastify.get('/regenerate', async (request, reply) => {
  await request.session.regenerate();
  request.session.set('userId', 123);
  await request.session.save();

  return reply.send();
});

For easier understanding on what is happening in the store:

    this.fastify.register(FastifySession, {
      secret: '...',
      store: {
        set: (sessionId, session, callback) => {
          console.log(`#set(${JSON.stringify(sessionId)}, ${JSON.stringify(session)}`);
          callback();
        },
        get: (sessionId, callback) => {
          console.log(`#get(${JSON.stringify(sessionId)})`);
          callback(null, null);
        },
        destroy: (sessionId, callback) => {
          console.log(`#destroy(${JSON.stringify(sessionId)})`);
          callback();
        }
      }
    });

Expected Behavior

I am essentially generating a completely new session with different ID and data/content.

I'd expect the session to be automatically deleted from the store as it is no longer used/needed.

As far as I can see, there is also no good workaround for this as calling await request.session.destroy(); before regenerating the session sets it to null causing TypeError: Cannot read properties of null (reading 'regenerate')

SpraxDev avatar Apr 08 '24 14:04 SpraxDev

A quick and dirty workaround:

let session = request.session;
await session.destroy();
await session.regenerate();
session = null; // just to make sure you don't use it or session = request.session

gabor-s avatar May 21 '24 15:05 gabor-s