Search code examples
next.jsoauth-2.0

NextJs: server component vs server action


recently im learning nextjs and i was trying to use authJs in my project for a simple google oauth signin. on all my attempts when i use this await signIn() i get errors talking about i can only use them in server actions or routes if im not wrong so i tried to add a "use server" on top of my component having this. finally finding this repo:

https://github.com/nextauthjs/next-auth/tree/main/apps/examples/nextjs i learned that what i was missing was that server components are different from server actions and i learned that components are serverComponent by default and ...

but can someone help me what is actually different between these two terms? or why i cant simply use that function inside a server component rather than specially a server action?


Solution

  • From the Next.js Router App docs:

    Server Actions are asynchronous functions that are executed on the server. They can be used in Server and Client Components to handle form submissions and data mutations in Next.js applications.

    React Server Components are React Components which render on the server. Server Actions are just plain functions, which are executed on the server, do something (often mutations) and optionally return something.

    A special kind of Server Actions are form handlers when invoked using the action attribute in a <form> element. If you want to access the return value by such a Server Action use Reacts useFormStatus hook.

    I hope this helps.