Build reactive applications with Convex for real-time data sync in Google Antigravity
# Convex Realtime Backend for Google Antigravity
Convex provides a reactive backend with real-time sync. This guide covers patterns for Google Antigravity IDE and Gemini 3.
## Schema Definition
```typescript
// convex/schema.ts
import { defineSchema, defineTable } from 'convex/server';
import { v } from 'convex/values';
export default defineSchema({
users: defineTable({
name: v.string(),
email: v.string(),
avatarUrl: v.optional(v.string()),
tokenIdentifier: v.string(),
})
.index('by_token', ['tokenIdentifier'])
.index('by_email', ['email']),
messages: defineTable({
content: v.string(),
authorId: v.id('users'),
channelId: v.id('channels'),
attachments: v.optional(v.array(v.string())),
})
.index('by_channel', ['channelId']),
channels: defineTable({
name: v.string(),
description: v.optional(v.string()),
isPrivate: v.boolean(),
memberIds: v.array(v.id('users')),
}),
});
```
## Query Functions
```typescript
// convex/messages.ts
import { query, mutation } from './_generated/server';
import { v } from 'convex/values';
export const list = query({
args: { channelId: v.id('channels'), limit: v.optional(v.number()) },
handler: async (ctx, { channelId, limit = 50 }) => {
const messages = await ctx.db
.query('messages')
.withIndex('by_channel', (q) => q.eq('channelId', channelId))
.order('desc')
.take(limit);
// Fetch authors for each message
const messagesWithAuthors = await Promise.all(
messages.map(async (message) => {
const author = await ctx.db.get(message.authorId);
return { ...message, author };
})
);
return messagesWithAuthors.reverse();
},
});
export const getById = query({
args: { messageId: v.id('messages') },
handler: async (ctx, { messageId }) => {
const message = await ctx.db.get(messageId);
if (!message) return null;
const author = await ctx.db.get(message.authorId);
return { ...message, author };
},
});
```
## Mutation Functions
```typescript
// convex/messages.ts (continued)
export const send = mutation({
args: {
content: v.string(),
channelId: v.id('channels'),
attachments: v.optional(v.array(v.string())),
},
handler: async (ctx, { content, channelId, attachments }) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error('Not authenticated');
const user = await ctx.db
.query('users')
.withIndex('by_token', (q) => q.eq('tokenIdentifier', identity.tokenIdentifier))
.unique();
if (!user) throw new Error('User not found');
const channel = await ctx.db.get(channelId);
if (!channel) throw new Error('Channel not found');
if (channel.isPrivate && !channel.memberIds.includes(user._id)) {
throw new Error('Not a member of this channel');
}
const messageId = await ctx.db.insert('messages', {
content,
authorId: user._id,
channelId,
attachments,
});
return messageId;
},
});
export const remove = mutation({
args: { messageId: v.id('messages') },
handler: async (ctx, { messageId }) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error('Not authenticated');
const message = await ctx.db.get(messageId);
if (!message) throw new Error('Message not found');
const user = await ctx.db
.query('users')
.withIndex('by_token', (q) => q.eq('tokenIdentifier', identity.tokenIdentifier))
.unique();
if (!user || message.authorId !== user._id) {
throw new Error('Not authorized');
}
await ctx.db.delete(messageId);
},
});
```
## React Hooks
```typescript
// app/components/MessageList.tsx
'use client';
import { useQuery, useMutation } from 'convex/react';
import { api } from '@/convex/_generated/api';
import { Id } from '@/convex/_generated/dataModel';
import { useState } from 'react';
export function MessageList({ channelId }: { channelId: Id<'channels'> }) {
const messages = useQuery(api.messages.list, { channelId });
const sendMessage = useMutation(api.messages.send);
const [content, setContent] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim()) return;
await sendMessage({ content, channelId });
setContent('');
};
if (messages === undefined) {
return <div>Loading...</div>;
}
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{messages.map((message) => (
<div key={message._id} className="flex gap-3">
<img
src={message.author?.avatarUrl || '/default-avatar.png'}
alt={message.author?.name}
className="w-10 h-10 rounded-full"
/>
<div>
<div className="font-semibold">{message.author?.name}</div>
<div>{message.content}</div>
</div>
</div>
))}
</div>
<form onSubmit={handleSubmit} className="p-4 border-t">
<input
type="text"
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
className="w-full px-4 py-2 border rounded"
/>
</form>
</div>
);
}
```
## Scheduled Functions
```typescript
// convex/crons.ts
import { cronJobs } from 'convex/server';
import { internal } from './_generated/api';
const crons = cronJobs();
crons.interval(
'cleanup old messages',
{ hours: 24 },
internal.messages.cleanupOld
);
export default crons;
// convex/messages.ts
import { internalMutation } from './_generated/server';
export const cleanupOld = internalMutation({
handler: async (ctx) => {
const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
const oldMessages = await ctx.db
.query('messages')
.filter((q) => q.lt(q.field('_creationTime'), thirtyDaysAgo))
.take(100);
for (const message of oldMessages) {
await ctx.db.delete(message._id);
}
},
});
```
## Best Practices
1. **Real-time Sync**: Automatic updates across clients
2. **Type Safety**: End-to-end TypeScript types
3. **Optimistic Updates**: Built into mutations
4. **Indexes**: Define indexes for query performance
5. **Cron Jobs**: Scheduled background tasks
6. **File Storage**: Built-in file upload/storage
Google Antigravity's Gemini 3 understands Convex patterns for reactive backends.This Convex 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 convex 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 Convex projects, consider mentioning your framework version, coding style, and any specific libraries you're using.