Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TTL interception for external conditional TTL handling #393

Merged
merged 2 commits into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ interface RedisStoreOptions {
prefix?: string
scanCount?: number
serializer?: Serializer
ttl?: number
ttl?: number | {(sess: SessionData): number}
disableTTL?: boolean
disableTouch?: boolean
}
Expand All @@ -31,7 +31,7 @@ class RedisStore extends Store {
prefix: string
scanCount: number
serializer: Serializer
ttl: number
ttl: number | {(sess: SessionData): number}
disableTTL: boolean
disableTouch: boolean

Expand Down Expand Up @@ -181,6 +181,10 @@ class RedisStore extends Store {
}

private _getTTL(sess: SessionData) {
if (typeof this.ttl === "function") {
return this.ttl(sess)
}

let ttl
if (sess && sess.cookie && sess.cookie.expires) {
let ms = Number(new Date(sess.cookie.expires)) - Date.now()
Expand Down
9 changes: 9 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ If the session cookie has a `expires` date, `connect-redis` will use it as the T

Otherwise, it will expire the session using the `ttl` option (default: `86400` seconds or one day).

```ts
interface RedisStoreOptions {
...
ttl?: number | {(sess: SessionData): number}
}
```

`ttl` also has external callback support. You can use it for dynamic TTL generation. It has access to `session` data.

**Note**: The TTL is reset every time a user interacts with the server. You can disable this behavior in _some_ instances by using `disableTouch`.

**Note**: `express-session` does not update `expires` until the end of the request life cycle. _Calling `session.save()` manually beforehand will have the previous value_.
Expand Down