TanStackT
TanStack10mo ago
3 replies
sad-indigo

Issues and questions regarding SSE in server function and API routes

Hi there!

Context: I'm building a web turn based 1v1 game. Behind the scenes, the way it would work is playing a move sends a POST request, the server will mutate the game state in the DB, and propagates changes to ther other client with SSE. I'm using version 1.114.25 in my project.

I've tried to use the example in the docs regarding streaming responses here: https://tanstack.com/start/latest/docs/framework/react/server-functions#returning-raw-response-objects, and using the EventSource API with a very simple useEffect for now:
useEffect(() => {
  // the url looks like this: /_server/src_routes_index_tsx--sse_createServerFn_handler
  const eventSource = new EventSource(sse.url);
  eventSource.onmessage = (event) => {
    console.log("Message received", event.data);
  };
  return () => {
    eventSource.close();
  };
}, []);

Unfortunately, it ends up with a 500 with this error in the console, even though there's no data :
Server Fn Error!

SyntaxError: "[object Object]" is not valid JSON


I've also tried to define the SSE as an API route using roughly the same code (mainly a ReadableStream and a Response with the appropriate headers). It does work fine, but I don't have a way to let that endpoint know that it should propagate an event, as it seems the API route is isolated from server functions. There's no server context to be shared, and I've also tried to define an Observable and subscribe to it in the API route but the observable is undefined (because it's defined outside of the API route handler scope I guess?).

Any help on setting up SSE properly with TS Start? Thanks!
What are Server Functions? Server functions allow you to specify logic that can be invoked almost anywhere (even the client), but run only on the server. In fact, they are not so different from an API...
Server Functions | TanStack Start React Docs
Was this page helpful?