Production-ready Server Actions patterns for forms, mutations, and data operations in Google Antigravity projects.
# Server Actions Form Handling for Google Antigravity
Server Actions provide a powerful way to handle form submissions and data mutations directly from React components. Google Antigravity's Gemini 3 integration helps you build type-safe, secure server actions with intelligent code generation.
## Basic Server Action Setup
Create server actions with proper validation and error handling:
```typescript
// app/actions/user-actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
const updateProfileSchema = z.object({
name: z.string().min(2).max(50),
bio: z.string().max(500).optional(),
website: z.string().url().optional().or(z.literal("")),
});
export type UpdateProfileState = {
errors?: {
name?: string[];
bio?: string[];
website?: string[];
_form?: string[];
};
success?: boolean;
};
export async function updateProfile(
prevState: UpdateProfileState,
formData: FormData
): Promise<UpdateProfileState> {
const session = await auth();
if (!session?.user?.id) {
return { errors: { _form: ["You must be logged in"] } };
}
const validatedFields = updateProfileSchema.safeParse({
name: formData.get("name"),
bio: formData.get("bio"),
website: formData.get("website"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
};
}
const { name, bio, website } = validatedFields.data;
try {
await prisma.user.update({
where: { id: session.user.id },
data: {
name,
profile: {
upsert: {
create: { bio, website },
update: { bio, website },
},
},
},
});
revalidatePath("/profile");
return { success: true };
} catch (error) {
return { errors: { _form: ["Failed to update profile"] } };
}
}
```
## Form Component with useFormState
Implement client-side form handling with server actions:
```typescript
// app/profile/edit/page.tsx
"use client";
import { useFormState, useFormStatus } from "react-dom";
import { updateProfile, UpdateProfileState } from "@/app/actions/user-actions";
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button
type="submit"
disabled={pending}
className="btn btn-primary"
>
{pending ? "Saving..." : "Save Changes"}
</button>
);
}
export default function EditProfilePage() {
const initialState: UpdateProfileState = {};
const [state, formAction] = useFormState(updateProfile, initialState);
return (
<form action={formAction} className="space-y-4">
{state.errors?._form && (
<div className="alert alert-error">
{state.errors._form.join(", ")}
</div>
)}
{state.success && (
<div className="alert alert-success">
Profile updated successfully!
</div>
)}
<div className="form-group">
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
className="input"
required
/>
{state.errors?.name && (
<p className="error">{state.errors.name[0]}</p>
)}
</div>
<div className="form-group">
<label htmlFor="bio">Bio</label>
<textarea
id="bio"
name="bio"
className="textarea"
rows={4}
/>
{state.errors?.bio && (
<p className="error">{state.errors.bio[0]}</p>
)}
</div>
<div className="form-group">
<label htmlFor="website">Website</label>
<input
type="url"
id="website"
name="website"
className="input"
placeholder="https://"
/>
{state.errors?.website && (
<p className="error">{state.errors.website[0]}</p>
)}
</div>
<SubmitButton />
</form>
);
}
```
## Optimistic Updates
Implement optimistic UI updates for better user experience:
```typescript
// app/actions/todo-actions.ts
"use server";
import { revalidatePath } from "next/cache";
import prisma from "@/lib/prisma";
export async function toggleTodo(id: string, completed: boolean) {
await prisma.todo.update({
where: { id },
data: { completed },
});
revalidatePath("/todos");
}
export async function deleteTodo(id: string) {
await prisma.todo.delete({
where: { id },
});
revalidatePath("/todos");
}
```
```typescript
// components/TodoItem.tsx
"use client";
import { useOptimistic, useTransition } from "react";
import { toggleTodo, deleteTodo } from "@/app/actions/todo-actions";
interface Todo {
id: string;
title: string;
completed: boolean;
}
export function TodoItem({ todo }: { todo: Todo }) {
const [isPending, startTransition] = useTransition();
const [optimisticTodo, setOptimisticTodo] = useOptimistic(
todo,
(state, newCompleted: boolean) => ({
...state,
completed: newCompleted,
})
);
const handleToggle = () => {
startTransition(async () => {
setOptimisticTodo(!optimisticTodo.completed);
await toggleTodo(todo.id, !todo.completed);
});
};
const handleDelete = () => {
startTransition(async () => {
await deleteTodo(todo.id);
});
};
return (
<div className={`todo-item ${isPending ? "opacity-50" : ""}`}>
<input
type="checkbox"
checked={optimisticTodo.completed}
onChange={handleToggle}
/>
<span className={optimisticTodo.completed ? "line-through" : ""}>
{todo.title}
</span>
<button onClick={handleDelete} disabled={isPending}>
Delete
</button>
</div>
);
}
```
## File Upload with Server Actions
Handle file uploads securely:
```typescript
// app/actions/upload-actions.ts
"use server";
import { writeFile } from "fs/promises";
import { join } from "path";
import { auth } from "@/lib/auth";
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp"];
export async function uploadAvatar(formData: FormData) {
const session = await auth();
if (!session?.user?.id) {
return { error: "Unauthorized" };
}
const file = formData.get("avatar") as File;
if (!file || file.size === 0) {
return { error: "No file provided" };
}
if (file.size > MAX_FILE_SIZE) {
return { error: "File too large (max 5MB)" };
}
if (!ALLOWED_TYPES.includes(file.type)) {
return { error: "Invalid file type" };
}
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
const filename = `${session.user.id}-${Date.now()}.${file.type.split("/")[1]}`;
const path = join(process.cwd(), "public/avatars", filename);
await writeFile(path, buffer);
return { success: true, url: `/avatars/${filename}` };
}
```
## Best Practices
1. **Always validate input** - Use Zod or similar for type-safe validation
2. **Handle authentication** - Check user session in every action
3. **Use revalidatePath/revalidateTag** - Keep UI in sync with server state
4. **Implement optimistic updates** - Improve perceived performance
5. **Return structured errors** - Enable proper error display in forms
Server Actions with Google Antigravity streamline full-stack development with intelligent form handling and mutation patterns.This server-actions prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their server-actions implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For server-actions projects, consider mentioning your framework version, coding style, and any specific libraries you're using.