Step 12 - Server Actions
Course: NextJS (Server side) - chapter 12
Ref - https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations
Right now, we wrote an API endpoint that let’s the user sign up
export async function POST(req: NextRequest) { const body = await req.json(); // should add zod validation here const user = await client.user.create({ data: { username: body.username, password: body.password } });
console.log(user.id);
return NextResponse.json({ message: "Signed up" });}What if you could do a simple function call (even on a client component that would run on the server?) (similar to RPC )
💡 Under the hood, still an HTTP request would go out. But you would feel like you’re making a function call
Steps to follow
Section titled “Steps to follow”- Create
actions/user.tsfile (you can create it in a different folder) - Write a function that takes
usernameandpasswordas input and stores it in the DB
"use server"
import client from "@/db"
export async function signup(username: string, password: string) { // should add zod validation here const user = await client.user.create({ data: { username: username, password: password } });
console.log(user.id);
return "Signed up!"}- Update the
Signup.tsxfile to do the function call
import { signup } from "@/actions/user";;
...
<button onClick={async () => { const response = await signup(username, password); localStorage.setItem("token", response); router.push("/")}} type="button" className="mt-8 w-full text-white bg-gray-800 focus:ring-4 focus:ring-gray-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2">Sign in</button>Check the network tab
Section titled “Check the network tab”
Benefits of server actions
Section titled “Benefits of server actions”- Single function can be used in both client and server components
- Gives you types of the function response on the frontend (very similar to trpc)
- Can be integrated seamlessly with forms (ref https://www.youtube.com/watch?v=dDpZfOQBMaU)