Skip to content

Commit 8664a9b

Browse files
Merge pull request #3433 from jyx-07/docs/sse-client-disconnection-cleanup
docs(sse): document client disconnection and observable cleanup
2 parents 024c826 + f275e1f commit 8664a9b

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

content/techniques/server-sent-events.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,24 @@ eventSource.onmessage = ({ data }) => {
4343
};
4444
```
4545

46+
#### Client disconnection
47+
48+
When a client closes the SSE connection (e.g., `eventSource.close()`), NestJS automatically unsubscribes from the returned Observable, which stops the event stream and cleans up any associated resources — including the interval timer in the example above.
49+
50+
To run custom teardown logic when a client disconnects, use the `finalize` operator:
51+
52+
```typescript
53+
@Sse('sse')
54+
sse(): Observable<MessageEvent> {
55+
return interval(1000).pipe(
56+
map((_) => ({ data: { hello: 'world' } })),
57+
finalize(() => console.log('Client disconnected')),
58+
);
59+
}
60+
```
61+
62+
> info **Hint** The `finalize` operator (imported from `rxjs`) executes its callback whenever the Observable terminates — by completion, error, or unsubscription (which includes client disconnect). This makes it the right place to release external resources such as database cursors or file handles tied to the stream.
63+
4664
#### Example
4765

4866
A working example is available [here](https://github.com/nestjs/nest/tree/master/sample/28-sse).

0 commit comments

Comments
 (0)