Skip to content
This repository was archived by the owner on Apr 26, 2026. It is now read-only.
This repository was archived by the owner on Apr 26, 2026. It is now read-only.

Support Server-Sent Events (SSE) in reactive data-driven mode #133

@danielfernandez

Description

@danielfernandez

By extending the data-driven mode already existing for Spring 5 (#132) Thymeleaf can support the rendering of Server-Sent Events (content type text/event-stream) that directly send HTML to the browser (instead of the more common JSON).

In scenarios in which the JSON sent by means of SSE is parsed and then used to render fragments of HTML (DOM) by means of a client-side template engine, Thymeleaf could completely save this client-side processing step by sending already-rendered HTML from the server using exactly the same template code used for normal server-side HTML rendering.

SSE events have the general following structure (see SSE):

event: [event_name]
id: [event_id]
data: [event_data_line]
data: [event_data_line]
data: [event_data_line]
data: [event_data_line]
...

When operating in data-driven mode in Spring WebFlux (see #132), Thymeleaf can use the th:each iteration performed on the reactive data driver variable (a Flux<?>) in order to generate three types of events and send their corresponding rendered HTML to the browser (which would be using a JavaScript EventSource object):

  • event: head for the single event containing the HTML rendered before the iteration (the th:each).
  • event: message for each of the events containing the HTML corresponding to each of the iterations, i.e. the HTML corresponding to each of the items produced by the Flux<?> data driver context/model variable.
  • event: tail: for the single event containing the HTML rendered after the iteration.

Note the use of the id field for the generated SSE events will allow browsers to adequately reconnect to the event source by specifying the Last-Event-ID HTTP header.

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions