Next.js Discord

Discord Forum

Are server actions sent to a client before execution?

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Avatar
Asiatic LionOP
Hey!

I'm reading nextjs docs and I don't understand something.

https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#closures-and-encryption

Below the example (see the link above), docs says:

...the captured variables are sent to the client and back to the server when the action is invoked.

I thought server actions run only on a server, like server components. Why would nextjs send captured variables inside of a server action to a client? Can you give me some information on this, please?

12 Replies

Avatar
Ray
the captured variable will be sent to client and render as a hidden input inside the form element.
So when the form submit, it will send the request to server with the value
Avatar
Asiatic LionOP
why send this variable to a client?
idk how server actions work under the hood. I thought they are just saved on a server somewhere and they invoke and do some stuff when you submit forms.
Avatar
Ray
from this example, publicVersion is defined outside of the function of server action
Image
if your server action doesn't use any value like this, no variable will be sent to client
Avatar
Asiatic LionOP
why publicVersion is being sent to a client if this variable is located in a server component that run only on a server? in jsx there's no sight of publishVersion, why send it?
im sorry, i dont understand
Avatar
Ray
Closures are useful when you need to capture a snapshot of data (e.g. publishVersion) at the time of rendering so that it can be used later when the action is invoked.
this is trying to prevent if the page open with a user and the data already updated by other user
so it throw an error if the page is not the latest version
so you don't need to render the version manually in the form
Avatar
Asiatic LionOP
I'll go and read on this more. Will try to run some examples on my machine. Still don't understand) Thanks for trying to help me
Avatar
Asiatic LionOP
what these hidden inputs for?

I thought when you send this line to a client
<button action={publish}>Publish</button
client will get smth like:
<button action={yourserverdomain.com/serveraction12345}>Publish</button>
So when you click a button, you just being redirected to some url where this server action is located
Avatar
Ray
yeah, you gotta try building something with form first