Skip to main content

Usage with forms

You can also pass an action to a form in a Server Component. Functionality is limited in this case, but it could be useful in some cases.

In this case, the action just receives form data as input.

In this example, we will use zod-form-data library as an "adapter" for Zod.

  1. Define the action.
"use server";

import { action } from "@/lib/safe-action";
import { z } from "zod";
import { zfd } from "zod-form-data";

const schema = zfd.formData({
email: zfd.text(z.string().email()),
password: zfd.text(z.string().min(8)),
});

export const signup = action
.schema(schema)
.define(async ({ email, password }) => {
console.log("Email:", email, "Password:", password);
// Do something useful here.
});
  1. Import it in a Server Component and use it as a Form Action.
import { signup } from "./signup-action";

export default function SignUpPage() {
return (
<form action={signup}>
<input type="text" name="email" placeholder="name@example.com" />
<input type="password" name="password" placeholder="••••••••" />
<button type="submit">Signup</button>
</form>
);
}