Confusion about `"use server"`
I have a few questions related to
"use server"
:
1. Should all server-only files be "use server"
? If not, why not?
2. I see that you can export anything other than a function from a module that is tagged with "use server"
, what's the reason for it?
3. Does "use server"
on a module expose all functions from that module to the public (e.g. they can be called from the outside in a RPC fashion)?
4. Should I only mark "use server"
functions that I intend to call on the client?4 Replies
I assume you've read https://docs.solidjs.com/solid-start/reference/server/use-server? It looks like you must
"use server"
on files/functions that get called from the client but must run on the server. I think it's optional (doesn't matter) whether you include it in functions that only get called on the server.
Regarding 2: I'm guessing it's because "use server"
only wraps functions with RPC, so any server-only state needs to be wrapped in a function to get it.I though
action
and query
is what wrapped the function into a RPC. Also if I omit use server
in functions that are called by other use server
functions it seems like SolidJS crashes silently while adding use server
makes it work so it's unclear whether that is actually required or not.Query is actually just there to dedupe request through a client side in memory cache.
Actions are there to update data in the client and update the cache through the actions response in a single fight ("single flight mutations") but they assure that functions run on the server.
So they are not making the functions to RPCs.
Without "use server" they‘ll run on the server only during the initial load, once hydrated in the browser they run on the client.
Only if you use "use server" they always they’ll be replaced with an RPC call once the app has hydrated in the browser.
I‘ve made a video showcasing this by returning the current time.
https://youtu.be/Qw9am5NL6AI?si=eDgwbULcLqewNm8-
Martin Rapp
YouTube
Data fetching in Solid-Start
In this video we cover the basics of the createAsync primitives,
server functions, cache wrapper, Suspense, ErrorBoundaries, route preloading and how they interact with each other.
Github repo: https://github.com/madaxen86/solid-tutorials/tree/master/data-fetching
Whether a function is included in the client bundle depends on where you import a function.
It’s a good practice to have your queries and actions separated from the e.g. pages.