Skip to content

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

  1. Create actions/user.ts file (you can create it in a different folder)
  2. Write a function that takes username and password as 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!"
}
  1. Update the Signup.tsx file 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>

  1. Single function can be used in both client and server components
  2. Gives you types of the function response on the frontend (very similar to trpc)
  3. Can be integrated seamlessly with forms (ref https://www.youtube.com/watch?v=dDpZfOQBMaU)