Skip to content

Commit 40607c1

Browse files
committed
doc(sse) Server-sent event feature
See nestjs/nest#4842
1 parent 201a55b commit 40607c1

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
### Server-Sent Events
2+
3+
You can enable Server-Sent events on a route with Nest. This can be used to push real-time updates to your client using HTTP. More informations about this specification can be found [on the whatwg website](https://html.spec.whatwg.org/multipage/server-sent-events.html).
4+
5+
#### Usage
6+
7+
In this example, we set a route named `/sse` that will allow you to propagate real time updates. These events can be listened to using the Javascript [EventSource API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource). On the `/` route, for the sake of the example, we're logging the received data in the browser's console.
8+
9+
Note the `@Sse` annotation that hooks the Server-Sent events mechanism on the choosed path:
10+
11+
```
12+
@Controller()
13+
export class AppController {
14+
@Get()
15+
getHello(): string {
16+
return `
17+
<script type="text/javascript">
18+
const ee = new EventSource('/sse')
19+
ee.onmessage = ({data}) => {
20+
console.log('New message', JSON.parse(data))
21+
}
22+
</script>
23+
`;
24+
}
25+
26+
@Sse('/sse')
27+
sse(): Observable<MessageEvent> {
28+
return interval(1000).pipe(map((_) => ({ data: { hello: 'world' } })));
29+
}
30+
}
31+
```
32+
33+
The events are sent via an Observable emitting a `MessageEvent`. The MessageEvent should respect the following interface to match the specification:
34+
35+
```
36+
export interface MessageEvent {
37+
data: string | object;
38+
id?: string;
39+
type?: string;
40+
retry?: number;
41+
}
42+
```
43+
44+
You can find a sample of a working example on [Nest repository](https://github.com/nestjs/nest/tree/master/sample/28-sse).

0 commit comments

Comments
 (0)