Skip to content

Commit

Permalink
fix: skip re-saving session when not modified since save
Browse files Browse the repository at this point in the history
When the `saveUninitialized` option is set to false, sessions will be
saved at the end of the request even when they have already been saved
earlier in the request and not subsequently modified. The result is a
double save that can potentially be wasteful with the persistence layer.
This change checks for modification of the session before saving, and
saves only if needed.
  • Loading branch information
jneander committed Oct 18, 2021
1 parent 0048bca commit fa1afd8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,10 @@ function session(options) {
return false;
}

if (savedHash) {
return !isSaved(req.session);
}

return !saveUninitializedSession && cookieId !== req.sessionID
? isModified(req.session)
: !isSaved(req.session)
Expand Down
23 changes: 23 additions & 0 deletions test/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -1775,6 +1775,29 @@ describe('session()', function(){
.expect(200, 'saved', done)
})
})

it('should prevent end-of-request save when saveUninitialized option is set to false', function (done) {
var store = new session.MemoryStore()
var server = createServer({ store: store, saveUninitialized: false }, function (req, res) {
req.session.hit = true
req.session.save(function (err) {
if (err) return res.end(err.message)
res.end('saved')
})
})

request(server)
.get('/')
.expect(shouldSetSessionInStore(store))
.expect(200, 'saved', function (err, res) {
if (err) return done(err)
request(server)
.get('/')
.set('Cookie', cookie(res))
.expect(shouldSetSessionInStore(store))
.expect(200, 'saved', done)
})
})
})

describe('.touch()', function () {
Expand Down

0 comments on commit fa1afd8

Please sign in to comment.