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:
Unfortunately, it ends up with a 500 with this error in the console, even though there's no data :
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!Server Functions | TanStack Start React Docs
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...
3 Replies
foreign-sapphire•6mo ago
I used an EventEmitter to create an event bus
The client register to events based on a sessionId (in my case is the auth session that i have access to during server functions and api routes)
In other parts of the app, eg server actions I publish on the event emitter based on that session id
https://gist.github.com/kandros/92590ce3d557dd6fbabe7f2339be87f1
optimistic-goldOP•6mo ago
Thanks for your answer Jaga!
So I took your Gist, but I ran into some issues, it wasn't super obvious what needed to be done to publish an event. I first wanted to use a server function to publish an event to the bus, but the Singleton instance wasn't shared between server functions and API routes (which was the issue I was running into earlier, it's not clear why though, I guess they are defined in different environments for Vite?). I moved to a POST route on the same API route handler and it does work now! I'll probably open an issue to have this called out in the docs.
foreign-sapphire•6mo ago
You might be right, I watched again my usage and it’s a bit more convoluted, I’m not emitting from server actions in my face probably havent faced this limitation
Afaik api and routes and server functions are bundled differently, I think one of the benefits of the vinxi removal is that they should be able to share modulues at runtime, but don’t quote me on that
Glad you made it work 👏