Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Server Actions Form Handling

Server Actions Form Handling

Production-ready Server Actions patterns for forms, mutations, and data operations in Google Antigravity projects.

server-actionsformsnextjsreactmutations
by antigravity-team
⭐0Stars
.antigravity
# 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.

When to Use This Prompt

This server-actions prompt is ideal for developers working on:

  • server-actions applications requiring modern best practices and optimal performance
  • Projects that need production-ready server-actions code with proper error handling
  • Teams looking to standardize their server-actions development workflow
  • Developers wanting to learn industry-standard server-actions patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the server-actions code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this server-actions prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...