fastify / fastify/session

Add lifecycle hooks for session observability

Open
#349 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
130
Forks
58
PR merge metrics
No merged PRs in 30d

Description

### Prerequisites

- [x] I have written a descriptive issue title
- [x] I have searched existing issues to ensure the feature has not already been requested

### 🚀 Feature Proposal

## Context
Important session events currently happen internally and are not visible to users. This makes production debugging, monitoring, and audit logging difficult.

Examples include session creation, loading, saving, expiration, destruction, regeneration, and store errors.

## Proposal
Add optional lifecycle hooks to the plugin configuration:

```js
fastify.register(session, {
secret,

hooks: {
onCreate(session, request) {},
onLoad(session, request) {},
onLoadMiss(sessionId, request) {},
onSave(session, request) {},
onDestroy(sessionId, request) {},
onRegenerate(oldId, newId, request) {},
onExpire(sessionId, request) {},
onCookieSkipped(reason, request) {},
onError(error, context, request) {}
}
})
```

Hooks should support synchronous and asynchronous functions. Hook failures should be reported through ```onError``` and should not break the session request flow.

## Events

- onCreate: a new session is initialized
- onLoad: an existing session is loaded
- onLoadMiss: the cookie exists but no session is found
- onSave: session data is persisted
- onDestroy: session data is removed
- onRegenerate: the session ID changes
- onExpire: an expired session is detected
- onCookieSkipped: the session cookie is not written
- onError: a store or lifecycle hook operation fails

### Motivation

I implemented lifecycle observability hooks in my own project and found them useful for integrating session events with logging, metrics, and tracing tools.

Providing this capability in the framework would allow other users to monitor session behavior and diagnose production issues without modifying the library internals.

### Example

_No response_

Contributor guide

Open the contributing guide

Research direction

Start at the fastify.register(session, ...) configuration entry point and trace where the listed session events occur. Define hook ordering, asynchronous behavior, and onError semantics for creation, loading, persistence, destruction, regeneration, expiration, cookie skipping, and store errors; done means all proposed hooks work without breaking the session request flow.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
backend, observability
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.