Skip to content

feat: Websocket Reconnect Events #4122

Closed

Description

@mgreystone

Describe the feature you'd like to request

I'm looking to perform an operation on a subscription when a websocket reconnects.

I have clients subscribing to a stream of events. I am sending the id of the last event received; my server will only emit events created after the given event id.

let lastEventId = getFromLocalState()

client.join.subscribe({ lastEventId }, {
  onData(event) {
    lastEventId = event.id
  },
})

However, whenever the websocket reconnects, the same lastEventId value that was used when the subscription was initially created is re-sent to the server. My server then re-sends events that we have already received. This occurs both when my server restarts & sends broadcastReconnectNotification as well as when the websocket is interrupted client-side.

Describe the solution you'd like to see

I'm looking for a reconnect handler that will allow me to define the subscription's behavior on re-connect.

It could have the following options:

  • Provide a mechanism to re-evaluate the subscription parameters once the connection to the websocket is re-established.
  • Provide a mechanism to not re-establish the subscription when a websocket is disconnected.

Some rough ideas....

let lastEventId = getFromLocalState()

client.join.subscribe({ lastEventId }, {
  onData(event) {
    lastEventId = event.id
  },
  onReconnect() {
    // return the new arguments for the resumed subscription
    return { lastEventId }
  }
})
let lastEventId = getFromLocalState()

const { unsubscribe } = client.join.subscribe({ lastEventId }, {
  onData(event) {
    lastEventId = event.id
  },
  onDisconnect() {
    // close this subscription
    unsubscribe()
    // create a new subscription with the latest parameters
    client.join.subscribe({ lastEventId }, { ... })
  }
})

Describe alternate solutions

This issue is similar to #1574, which proposes re-evaluating subscription parameters all the time. I think this would solve the problem but doesn't give the subscription any insight into the state of the websocket.

(The workaround described in the description doesn't work for me, as onError is not dispatched when broadcastReconnectNotification is invoked.)

Additional information

No response

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR implementing this feature!

TRP-17

Activity

  1. mgreystone commented on Apr 4, 2023

    @mgreystone
    Author

    Open discussion: #4127

  2. Elvincth commented on Apr 9, 2023

    @Elvincth

    +1 for this

  3. added
    ✅ accepted-PRs-welcome
    and removed on Apr 17, 2023
  4. mozzius commented on Apr 18, 2023

    @mozzius
    Contributor

    Could the first argument of subscribe optionally be a function, like useState? You'd call it each time a connection is established to get the latest params.

    client.join.subscribe(() => ({ lastEventId: getLastEvent() }), {
      onData(event) {
        setLastEvent(event.id)
      },
    })
  5. changed the title [-]feat: Websocket Reconnect Events[/-] [+][TRP-17] feat: Websocket Reconnect Events[/+] on May 25, 2023
  6. changed the title [-][TRP-17] feat: Websocket Reconnect Events[/-] [+]feat: Websocket Reconnect Events[/+] on May 25, 2023
  7. sneko commented on Feb 19, 2024

    @sneko

    I'm also looking for reactivity on parameters change over subscriptions. Or a way to have some control over it, like a .stop() so I could try to hack a bit.

    @mgreystone did you find a workaround in the meantime?

  8. mgreystone commented on Feb 22, 2024

    @mgreystone
    Author

    @sneko

    Investigated what it would take to expose some visibility of the websocket state to the subscriber. But i found that the subscriber & the websocket client are (reasonably) kept pretty distant from each other,
    & it would take a lot of changes to make this work.

    So i did end up with a workaround. When the subscriptions onStarted callback is invoked (which will happen every connection/reconnection), i call a resume mutation with whatever state my client was last in. The server then receives that state & starts pushing changes to the browser over the websocket subscription.

    So something like...

    server

    const emitter = new EventEmitter()
    
    const join = procedure.input(
        z.object({
          name: z.string()
        }),
      )
      .subscription(({ input }) => {
        return observable((emit) => {
          emitter.on(`resume:${input.name}`, resume)
    
          return () => {
            unsubscribe()
            emitter.off(`resume:${input.name}`, resume)
          }
    
          function resume(sinceVersion: number): void {
            // start emitting stuffs
          }
        })
      })
    
    const resume = procedure
      .input(
        z.object({
          sinceVersion: z.number(),
          name: z.string(),
        }),
      )
      .mutation(({ input }) => {
        emitter.emit(
          `resume:${input.name}`,
          input.sinceVersion,
        )
      })

    browser

    let lastReceivedVersion = initialVersion
    
    const unsub = client.join.subscribe(
      { name },
      {
        onStarted() {
          client.resume.mutate({
            name,
            sinceVersion: lastReceivedVersion,
          })
        },
        onData({ version, ...rest }) {
          lastReceivedVersion = version
          // do stuffs with `rest`
        },
      },
    )
  9. KATT commented on Nov 2, 2026

    @KATT
    Member

    🤖 Supported in v11: yield events with tracked() and wsLink re-sends the last lastEventId in the input when it reconnects.

    .input(z.object({ lastEventId: z.string().nullish() }).optional())
    .subscription(async function* (opts) {
      for await (const [post] of on(ee, 'add', { signal: opts.signal })) {
        yield tracked(post.id, post);
      }
    })

    Docs: https://trpc.io/docs/server/subscriptions#tracked. Closing.

  10. github-actions commented on Nov 4, 2026

    @github-actions
    Contributor

    This issue has been locked because we are very unlikely to see comments on closed issues. If you are running into a similar issue, please create a new issue. Thank you.

  11. locked as resolved and limited conversation to collaborators on Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    @trpc/client@trpc/react-query✅ accepted-PRs-welcome

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions