'Provide Last-Event-Id to EventSource constructor

Is it possible to set the Last-Event-Id header of an EventSource ? I have a simple chat app that keeps the messages cached. When I connect, I send all the chat since the Last-Event-Id, or all of them if it is not provided.

Since I keep the messages, I figured I might be able to pass the Id to the EventSource constructor to avoid it giving me back all the messages I already have. Is that simply not possible ?



Solution 1:[1]

The EventSource request will only have the Last-Event-Id header if the connection breaks and the client will have to reconnect. You can "force" this reconnection by letting the server break the first connection.

It goes like this:

  1. Create a connection using EventSource.
  2. The server receives the request and test if the Last-Event-Id is a request header.
    • If the Last-Event-Id is present:
      • get the value/id.
      • send events from the server according to the id.
    • If the Last-Event-Id is not present:
      • send an event containing an id (the id that you consider to be the last id).
      • make the server break/finish the connection.
  3. If the connection is broken by the server the client will try to reconnect with a new request. This time the request will have a Last-Event-Id header, and now you jump up to number 2.

The only problem with this approach is the delay caused by the client because it has to make two connections. I haven't tested the delay, but it looks like something around 3-5 seconds between each request.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chrwahl