Reputation: 31
At first glance I under the impression that Server Actions
are just function written on server, to be executed on the server by some other server code or Server Component.
from NextJs docs
To my surprise, Server Action
can also be called by the Client component (maked as 'use client'
).
This has left me all confused. How can an server function be called by a code running on browser? Seems like I am missing something. I couldn't find anything online about it.
So my question is:
How is Client component (browser code) able to call Server Actions
(server code)? Would love to see some write up or a reference?
Upvotes: 2
Views: 2480
Reputation: 5008
Since you're looking for a technical explanation rather than a code sample, here is a sufficiently detailed text on the topic from one of the core Next.js devs: https://github.com/vercel/next.js/discussions/54075 (look under The mutations I trigger
> Invalidation
> Server Actions (revalidatePath / revalidateTag)
> How it works
).
Even though it largely describes Server Actions in the context of caching and cache invalidation, this is probably the best source I found on the topic overall.
I'm going to copy the most relevant parts here, just in case something happens to that discussion.
"use server"
adds a marker to the function at compile time and move it into a separate module. All Server Actions have their own unique ID so that they can be referred to individually. (This explanation is heavily simplified, reality is a bit more involved)- When you call the function it will do a POST request to the current URL with the Server Action ID, that allows Next.js to call the right underlying function.
- Example of calling the function: The
<form action={serverAction}>
is submitted or you manually callserverAction()
in a client component- While calling the function you’ve defined to be a Server Action a few things can happen
- [...]
- The function returns a result
- You can return your own response from Server Actions, this could be an object, but could also be JSX, anything valid to be serialized from Server Component to Client Component is also a valid return value for Server Actions.
- [...]
- In order to use the result you have to manually call the Server Action, this does not apply to passing the Server Action directly to the
action
prop in<form action={serverAction}>
Upvotes: 0
Reputation: 8683
Client Components, despite the unfortunate naming, does not run only on the browser. Please correct me if I'm wrong.
As mentioned here,
Despite their name, "client components" (which, IMHO, is unfortunate) are also server-rendered, and they run on both the server and the client.
I found these 2 videos that explain the concept well from the other answer recommended by StackOverflow AI:
Upvotes: -1