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
Convex Reactive Database Patterns

Convex Reactive Database Patterns

Build real-time reactive applications with Convex backend in Google Antigravity with automatic sync and optimistic updates

ConvexReal-timeDatabaseReactBackend
by Antigravity Team
⭐0Stars
.antigravity
# Convex Reactive Database Patterns for Google Antigravity

Real-time data synchronization creates engaging user experiences but is traditionally complex to implement. This guide establishes patterns for integrating Convex with Google Antigravity projects, enabling Gemini 3 to generate reactive backends with automatic data sync.

## Schema Definition

Define type-safe schemas with Convex:

```typescript
// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  users: defineTable({
    clerkId: v.string(),
    email: v.string(),
    name: v.string(),
    avatarUrl: v.optional(v.string()),
    createdAt: v.number(),
  })
    .index("by_clerk_id", ["clerkId"])
    .index("by_email", ["email"]),

  messages: defineTable({
    channelId: v.id("channels"),
    authorId: v.id("users"),
    content: v.string(),
    attachments: v.optional(v.array(v.string())),
    createdAt: v.number(),
    updatedAt: v.optional(v.number()),
  })
    .index("by_channel", ["channelId", "createdAt"])
    .index("by_author", ["authorId"]),

  channels: defineTable({
    name: v.string(),
    description: v.optional(v.string()),
    isPrivate: v.boolean(),
    members: v.array(v.id("users")),
    createdBy: v.id("users"),
    createdAt: v.number(),
  })
    .index("by_name", ["name"])
    .searchIndex("search_name", { searchField: "name" }),

  presence: defineTable({
    userId: v.id("users"),
    channelId: v.id("channels"),
    lastSeen: v.number(),
    isTyping: v.boolean(),
  })
    .index("by_channel", ["channelId"])
    .index("by_user", ["userId"]),
});
```

## Query Functions

Create reactive queries that automatically update:

```typescript
// convex/messages.ts
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";
import { paginationOptsValidator } from "convex/server";

export const listByChannel = query({
  args: {
    channelId: v.id("channels"),
    paginationOpts: paginationOptsValidator,
  },
  handler: async (ctx, args) => {
    const messages = await ctx.db
      .query("messages")
      .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
      .order("desc")
      .paginate(args.paginationOpts);

    // Enrich messages with author data
    const enrichedMessages = await Promise.all(
      messages.page.map(async (message) => {
        const author = await ctx.db.get(message.authorId);
        return { ...message, author };
      })
    );

    return { ...messages, page: enrichedMessages };
  },
});

export const send = mutation({
  args: {
    channelId: v.id("channels"),
    content: v.string(),
    attachments: v.optional(v.array(v.string())),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Unauthenticated");

    const user = await ctx.db
      .query("users")
      .withIndex("by_clerk_id", (q) => q.eq("clerkId", identity.subject))
      .unique();

    if (!user) throw new Error("User not found");

    const messageId = await ctx.db.insert("messages", {
      channelId: args.channelId,
      authorId: user._id,
      content: args.content,
      attachments: args.attachments,
      createdAt: Date.now(),
    });

    // Update typing indicator
    await ctx.db
      .query("presence")
      .withIndex("by_user", (q) => q.eq("userId", user._id))
      .unique()
      .then(async (presence) => {
        if (presence) {
          await ctx.db.patch(presence._id, { isTyping: false });
        }
      });

    return messageId;
  },
});
```

## React Integration

Use Convex hooks for reactive UI:

```typescript
// components/ChatMessages.tsx
"use client";

import { useQuery, useMutation, usePaginatedQuery } from "convex/react";
import { api } from "@/convex/_generated/api";
import { Id } from "@/convex/_generated/dataModel";
import { useCallback, useRef, useEffect } from "react";

interface ChatMessagesProps {
  channelId: Id<"channels">;
}

export function ChatMessages({ channelId }: ChatMessagesProps) {
  const { results, status, loadMore } = usePaginatedQuery(
    api.messages.listByChannel,
    { channelId },
    { initialNumItems: 50 }
  );

  const sendMessage = useMutation(api.messages.send);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [results, scrollToBottom]);

  const handleSend = async (content: string) => {
    await sendMessage({ channelId, content });
  };

  return (
    <div className="flex flex-col h-full">
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {status === "CanLoadMore" && (
          <button onClick={() => loadMore(50)} className="text-blue-500">
            Load earlier messages
          </button>
        )}
        {results?.map((message) => (
          <MessageBubble key={message._id} message={message} />
        ))}
        <div ref={messagesEndRef} />
      </div>
      <MessageInput onSend={handleSend} />
    </div>
  );
}
```

## Best Practices

1. **Schema design**: Use indexes for efficient queries
2. **Pagination**: Implement pagination for large datasets
3. **Optimistic updates**: Leverage Convex's built-in optimistic updates
4. **Authentication**: Integrate with Clerk or Auth0 for identity
5. **Error handling**: Handle network errors gracefully

When to Use This Prompt

This Convex prompt is ideal for developers working on:

  • Convex applications requiring modern best practices and optimal performance
  • Projects that need production-ready Convex code with proper error handling
  • Teams looking to standardize their convex development workflow
  • Developers wanting to learn industry-standard Convex 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 convex 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 Convex 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 Convex 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 Convex projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...