Different server context when using "use server"?
Hi, I was trying to create a simple game project where player lobbies would (for simplicity) be saved on the server. Then I wanted to create some RPC using the "use server" so I can for example check whether the specific lobby exists etc.
But I encountered that the state of the variable differed in the RPC functions and the rest of the server context, let me show an example on random number variable.
src/server/number.ts
Then I created API endpoints just to be able to easily check whether the numbers match
src/routes/api/getRandomNumber.ts
This is the RPC for getting the random number
src/routes/utils/callbacks.ts
Lastly I have a page where I get the data from both sources so I can check whether they match
And this was the result:
RPC: 0.7921163507084992
API: 0.4117746060818235
This probably comes from my lack of knowledge but I would really appreciate any explanation why does it behave that way and what is the proper way to handle it/change it to more suitable solution.
Thank you in advance.
4 Replies
This is just a behaviour of start/vinxi at the moment, I think server functions and api routes use separate builds so they can’t really have shared state like that. There’s an issue open about it somewhere
Oh, ok, thank you for the response, do you have any recommendation how to approach it then, just pick one of these and stick with it?
While I'm not fluent with vinxi's internals (and how SolidStart wraps it) my experience suggest that server actions and routes are handled by separate workers.
For the purpose of a demonstration project I simply used BroadcastChannel to communicate between the distinct workers, i.e.:
https://github.com/peerreynders/server_-routes-lobotomy
That said I'm viewing the SolidStart server side not as the Backend but as the Backend for the Frontend. In most cases the real Backend exists outside of SolidStart anyway—at that point any SolidStart server-side worker can access the Backend separately and independently.
MDN Web Docs
Broadcast Channel API - Web APIs | MDN
The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin.
GitHub
GitHub - peerreynders/server_-routes-lobotomy: Demonstration of bri...
Demonstration of bridging communication between the isolated server and routes processing - peerreynders/server-routes-lobotomy
@peerreynders Thank you very much for the response, I will look into it ❤️