Skip to content

Make sure we set session cookie if saveUninitialized is false and maxAge is on #147

Description

@rclmenezes

Prerequisites

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

Fastify version

4

Plugin version

9

Node.js version

16

Operating system

Linux

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

Description

Currently, if maxAge is on and saveUninitialized is false, we don't re-save the session.

See this for original discussion:
#144 (comment)

Fix is putting the cookie's expiration in the hash:

if (this === sess && key === 'cookie') {
        // we want `touch` to affect the hash of the session
        return sess.cookie.expires?.getTime()
      }
}

Steps to Reproduce

test('should set session cookie if saveUninitialized is false and maxAge is on', async (t) => {
  t.plan(2)
  const options = {
    cookie: {
      maxAge: 42
    },
    secret: 'cNaoPYAwF60HZJzkcNaoPYAwF60HZJzk',
    saveUninitialized: false
  }
  const plugin = fastifyPlugin(async (fastify, opts) => {
    fastify.addHook('onRequest', (request, reply, done) => {
      request.sessionStore.set(DEFAULT_SESSION_ID, {
        // In this scenario, maxAge would have set expires in a previous request
        cookie: {
          expires: new Date(Date.now() + 1000)
        }
      }, done)
    })
  })
  const fastify = await buildFastify((request, reply) => reply.send(200), options, plugin)
  t.teardown(() => fastify.close())

  const response = await fastify.inject({
    url: '/',
    headers: { cookie: DEFAULT_COOKIE, 'x-forwarded-proto': 'https' }
  })

  t.equal(response.statusCode, 200)
  t.ok(response.headers['set-cookie'])
})

Expected Behavior

The session should re-save

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions