The .antigravity rules file is your secret weapon for unlocking the full potential of Google Antigravity IDE. This comprehensive guide will teach you everything you need to know about creating powerful, effective rules that transform Gemini 3 into your perfect coding partner.
A .antigravity file is a configuration file that lives in your project root and tells Google Antigravity how to behave when working on your codebase. Think of it as a personalized instruction manual for your AI assistant.
Without a rules file, Gemini 3 uses generic patterns. With a well-crafted .antigravity file, you get:
Every .antigravity file follows a simple structure:
# Project Context
Brief description of your project and its purpose.
## Tech Stack
- Framework: Next.js 14 with App Router
- Language: TypeScript 5.0+
- Styling: Tailwind CSS
- Database: Supabase (PostgreSQL)
## Code Style Guidelines
- Use functional components with hooks
- Prefer named exports over default exports
- Use async/await over .then() chains
## File Organization
- Components in /src/components
- Pages in /src/app
- Utilities in /src/lib
## Naming Conventions
- Components: PascalCase (UserProfile.tsx)
- Functions: camelCase (getUserData)
- Constants: SCREAMING_SNAKE_CASE (API_BASE_URL)
Start with context about what your project does:
# Project: E-Commerce Platform
This is a modern e-commerce platform built for selling digital products.
The target users are creators and small businesses.
Key features:
- User authentication with OAuth
- Product catalog with search
- Stripe payment integration
- Admin dashboard
Why this matters: Gemini 3 uses this context to understand the business logic behind your code requests.
Be explicit about your technology choices:
## Technology Stack
### Frontend
- Next.js 14.2+ (App Router only, no Pages Router)
- React 18 with Server Components
- TypeScript 5.3+ (strict mode)
- Tailwind CSS 3.4
- Shadcn/ui components
### Backend
- Next.js API Routes & Server Actions
- Supabase for database and auth
- Stripe for payments
- Resend for emails
### Testing
- Vitest for unit tests
- Playwright for E2E tests
Pro tip: Include version numbers to prevent outdated code suggestions.
Define your coding standards clearly:
## Code Style
### TypeScript
- Always use explicit return types for functions
- Prefer interfaces over type aliases for objects
- Use `const` assertions for literal types
- Never use `any` - use `unknown` if type is truly unknown
### React
- Functional components only (no class components)
- Use named exports: `export function Component()`
- Props interfaces named: `ComponentNameProps`
- Keep components under 200 lines
### Imports
- Group imports: React, third-party, local, types
- Use absolute imports with @/ alias
- No default exports except for pages
Document your architectural decisions:
## Architecture
### State Management
- Server state: React Query / TanStack Query
- Client state: Zustand (no Redux)
- Form state: React Hook Form + Zod
### Data Fetching
- Use Server Components for initial data
- Use Server Actions for mutations
- Client-side fetching only when necessary
### Error Handling
- Use Result pattern for expected errors
- Throw only for unexpected errors
- Always provide user-friendly error messages
Help Gemini understand your project organization:
## Project Structure
src/ āāā app/ # Next.js App Router pages ā āāā (auth)/ # Auth group routes ā āāā (dashboard)/ # Dashboard group routes ā āāā api/ # API routes āāā components/ ā āāā ui/ # Reusable UI components ā āāā forms/ # Form components ā āāā layouts/ # Layout components āāā lib/ ā āāā supabase/ # Supabase client & helpers ā āāā stripe/ # Stripe integration ā āāā utils/ # Utility functions āāā hooks/ # Custom React hooks āāā types/ # TypeScript type definitions āāā styles/ # Global styles
### Naming Patterns
- Page components: `page.tsx` (Next.js convention)
- Layout components: `layout.tsx`
- Loading states: `loading.tsx`
- Error boundaries: `error.tsx`
Use markdown headers to scope rules:
## When Writing API Routes
- Always validate request body with Zod
- Return consistent error format: { error: string, code: number }
- Include rate limiting for public endpoints
- Log all errors to monitoring service
## When Writing React Components
- Extract logic to custom hooks when > 20 lines
- Use memo() only when profiler shows need
- Prefer composition over prop drilling
Show Gemini exactly what you want:
## Component Template
When creating new components, follow this pattern:
```tsx
'use client';
import { useState } from 'react';
import { cn } from '@/lib/utils';
interface ButtonProps {
variant?: 'primary' | 'secondary';
size?: 'sm' | 'md' | 'lg';
children: React.ReactNode;
onClick?: () => void;
className?: string;
disabled?: boolean;
}
export function Button({
variant = 'primary',
size = 'md',
children,
onClick,
className,
disabled = false,
}: ButtonProps) {
return (
<button
onClick={onClick}
disabled={disabled}
className={cn(
'rounded-lg font-medium transition-colors',
variants[variant],
sizes[size],
className
)}
>
{children}
</button>
);
}
### Pattern 3: Anti-Patterns Section
Tell Gemini what NOT to do:
```markdown
## Anti-Patterns (NEVER DO)
ā Never use `var` - always `const` or `let`
ā Never use `any` type
ā Never use inline styles - use Tailwind classes
ā Never mutate state directly
ā Never use `document.querySelector` in React
ā Never store sensitive data in localStorage
ā Never use `// @ts-ignore` without explanation
ā Never commit .env files
Define business terms:
## Domain Glossary
- **Workspace**: A collection of projects owned by a team
- **Project**: A single codebase or application
- **Member**: A user who belongs to a workspace
- **Credits**: Usage units for AI features (1 credit = 1 request)
- **Plan**: Subscription tier (Free, Pro, Enterprise)
# SaaS Boilerplate - .antigravity Rules
## Project Overview
Multi-tenant SaaS application with subscription billing.
## Tech Stack
- Next.js 14 (App Router)
- TypeScript (strict)
- Tailwind CSS + Shadcn/ui
- Supabase (Auth + Database)
- Stripe (Subscriptions)
- Resend (Transactional Email)
## Authentication Rules
- Use Supabase Auth exclusively
- Implement row-level security (RLS) for all tables
- Never expose user IDs in URLs - use slugs
- Session tokens in httpOnly cookies only
## Database Rules
- All tables must have: id, created_at, updated_at
- Use UUID for primary keys
- Soft delete with deleted_at column
- Index all foreign keys
## API Design
- RESTful conventions for CRUD
- Server Actions for mutations
- Consistent response format:
{ success: boolean, data?: T, error?: string }
## Security Requirements
- Validate all inputs with Zod
- Sanitize user-generated content
- Rate limit all public endpoints
- CSRF protection on forms
# Component Library - .antigravity Rules
## Purpose
Reusable component library for internal applications.
## Design System
- Follow Material Design 3 principles
- Use CSS custom properties for theming
- Support light/dark mode
- Minimum touch target: 44x44px
## Component Requirements
- Every component must have:
- TypeScript interface for props
- Storybook story
- Unit tests (>80% coverage)
- JSDoc comments
- Keyboard accessibility
## Accessibility Standards
- WCAG 2.1 AA compliance minimum
- All interactive elements focusable
- Proper ARIA labels
- Support reduced motion preference
## Export Pattern
```tsx
// components/Button/index.ts
export { Button } from './Button';
export type { ButtonProps } from './Button.types';
### Example 3: Python FastAPI Backend
```markdown
# FastAPI Backend - .antigravity Rules
## Project Type
REST API backend for mobile application.
## Tech Stack
- Python 3.11+
- FastAPI 0.100+
- SQLAlchemy 2.0 (async)
- PostgreSQL 15
- Redis (caching)
- Celery (background tasks)
## Code Style
- Follow PEP 8
- Use type hints everywhere
- Docstrings in Google format
- Max line length: 88 (Black formatter)
## API Conventions
- Versioned endpoints: /api/v1/
- Snake_case for JSON fields
- Pagination: ?page=1&per_page=20
- ISO 8601 for dates
## Error Handling
```python
class APIError(Exception):
def __init__(self, message: str, code: str, status: int = 400):
self.message = message
self.code = code
self.status = status
## Common Mistakes to Avoid
### Mistake 1: Being Too Vague
ā **Bad:**
```markdown
Use good code practices.
ā Good:
- Functions must have single responsibility
- Max function length: 50 lines
- Max file length: 300 lines
- Cyclomatic complexity < 10
ā Bad:
Use default exports for components.
Never use default exports.
ā Good:
Export rules:
- Page components: default export (Next.js requirement)
- All other components: named exports only
ā Bad:
Use getServerSideProps for data fetching.
ā Good:
Use Server Components and async functions for data fetching.
getServerSideProps is legacy - use App Router patterns.
Review your .antigravity file monthly. As your project evolves, so should your rules.
Commit your .antigravity file to version control. Everyone benefits from consistent AI assistance.
## Database Queries
<!-- Updated 2025-01: Switched from Prisma to Drizzle -->
- Use Drizzle ORM for all database operations
- Prefer select() over findMany() for performance
After updating rules, test with common prompts:
Begin with basic rules and add complexity as you discover patterns. Over-engineering upfront leads to rules that are hard to maintain.
Place it in your project root directory, alongside your package.json or pyproject.toml.
Yes! You can have subdirectory-specific rules. Antigravity will merge rules, with more specific files taking precedence.
Aim for 100-300 lines. Too short misses opportunities; too long becomes hard to maintain.
No! Share it with your team. The whole point is consistent AI assistance across developers.
Review monthly, update when you:
A well-crafted .antigravity rules file transforms Google Antigravity from a generic AI assistant into a specialized coding partner that understands your project deeply. Start with the basics, iterate based on your needs, and watch your productivity soar.
Ready to level up? Check out our collection of .antigravity rules for inspiration, or explore MCP servers to extend Antigravity's capabilities even further.
Last updated: December 2024 Found this helpful? Share it with your team!