Next.js Discord

Discord Forum

Why are server actions needed if I have regular page file?

Answered
Poodle posted this in #help-forum
Open in Discord
PoodleOP
I’m relatively new to app router development and don’t fully understand the purpose of server actions when the file is a regular page. I encountered this while working with Supabase. I have a login page where I want to call the Supabase login function, but in their docs, they add "use server" to the function. Why is that necessary? Isn’t the file already a server file?
Answered by luis_llanes
What “use server” does is taking the exported async function and exposing it as a public POST endpoint.

Might be confusing at first to see “use server” and “use client” and thinking they’re opposites to each other, that’s not it tho.

“use server” makes sure the exported async functions run on the server, even if you call it from the client because under the hood it became an API endpoint.
View full answer

6 Replies

Short mackerel
It is needed, because when a user wants to log in, the button that triggers the click event must be inside a client component, which in turn is not a server.
Whatever request is being sent from a client component, the request is cleartext visible on the browser.
For security purposes, and honestly better readability, you would call the function in a server action with the “use server” directive, which in turn is called in a client component.
Rose-breasted Grosbeak
if you're new to react itself, then next js is not a good place to start, first get familiar with react, SPAs, and MPAs
What “use server” does is taking the exported async function and exposing it as a public POST endpoint.

Might be confusing at first to see “use server” and “use client” and thinking they’re opposites to each other, that’s not it tho.

“use server” makes sure the exported async functions run on the server, even if you call it from the client because under the hood it became an API endpoint.
Answer
And yeah, when the user wants to log in or log out these “server actions” need to be called from the client because they’re accessing and manipulating cookies which can only happen if you have access to the Request Information such a cookies/headers that are in the browser, not the server
PoodleOP
Appreciate the help guys! It became a lot clearer now, especially realizing that use client and use server are not opposites but rather used for different use cases.
Yes, once you internalize that it all becomes easier.

“use server” -> creates public POST endpoints for all exported async functions within that file (or just the function when individually annotated with it)

“use client” -> sent this code chunk (with all the JS and dependencies) to the client to Hydrate and make it interactive