A production-ready template featuring event-driven broker architecture, designed for rapid AI-assisted development. Build full-stack applications with Next.js frontend and Python Firebase Functions backend using parallel AI agents.
- π€ AI-First Development - Optimized for multi-agent parallel development
- π Event-Driven Architecture - Database as single source of truth
- π Built-in AI Rules - PRD, ADR, and task templates for AI agents
- π Real-time Updates - Firestore subscriptions for automatic UI updates
- π Firebase Authentication - Email/Password & Google Sign-In
- π Firestore Database - Real-time NoSQL with subscription hooks
- π Firebase Storage - File upload and management
- π¨ Material-UI (MUI) - Modern React components
- π State Management - React Context for auth
- π TypeScript - Full type safety
- π Next.js 14 - App Router with server components
- β‘ Serverless Functions - Auto-scaling Python backend
- ποΈ Broker Architecture - Event-driven, decoupled design
- π DocumentBase Classes - Structured Firestore management
- π Authentication Wrappers - Built-in security
- π§ͺ Integration Testing - Real API testing with emulators
- π¦ Pydantic Models - Runtime validation
- π― TDD Workflow - Test-first development
- Node.js 18+
- Python 3.9+
- Firebase account (sign up at Firebase Console)
- Firebase CLI (
npm install -g firebase-tools)
- Go to Firebase Console
- Click "Create a project" or "Add project"
- Enter your project name
- Choose whether to enable Google Analytics (optional)
- Wait for the project to be created
- Go to Authentication > Sign-in method
- Enable Email/Password provider
- Enable Google provider (optional but recommended)
- Go to Firestore Database > Create database
- Choose Start in test mode for development
- Select a location closest to your users
- Note: You'll secure it with rules before production
- Go to Storage > Get started
- Start in test mode
- Choose the same location as your Firestore database
- Go to Functions > Get started
- Note: Requires Blaze (Pay as you go) plan
- Firebase has generous free tiers
- Required for Functions and advanced features
- Follow the setup instructions
- In your Firebase project, click βοΈ > Project settings
- Scroll to "Your apps" section
- Click Web icon
</> - Register your app with a nickname
- Copy the Firebase configuration object
# Clone the repository
git clone <your-repo-url>
cd <project-directory>
# Install Firebase CLI globally
npm install -g firebase-tools
# Login to Firebase
firebase login
# Configure Firebase project
# Edit .firebaserc and replace with your project IDNavigate to the frontend directory:
cd front
# Install dependencies
yarn install
# or
npm install
# Create environment file
cp .env.example .env.localOpen front/.env.local and add your Firebase configuration:
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key_here
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=123456789
NEXT_PUBLIC_FIREBASE_APP_ID=1:123456789:web:abcdef
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXXyarn dev
# or
npm run devVisit http://localhost:3000 to see your app.
cd back
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt- Go to Firebase Console > Project Settings > Service Accounts
- Click "Generate new private key" and download the JSON file
- Place the JSON file in the
back/directory - Create
.envfile inback/directory:
cp .env.example .env
# Edit .env and add:
# FIREBASE_SERVICE_ACCOUNT_PATH=./your-service-account-key.json
# Add any other API keys your project needs# Start Firebase emulators (required for testing)
firebase emulators:start
# In another terminal, run tests
cd back
source venv/bin/activate
# Run all tests with emulators (recommended)
python run_tests.py
# Run only unit tests (fast, no emulator needed)
python run_tests.py --test-type unit --no-emulator
# Run only integration tests
python run_tests.py --test-type integration
# Manual testing with pytest
pytest # Ensure emulators are running first# Deploy functions only
firebase deploy --only functions
# Deploy security rules
firebase deploy --only firestore:rules,storage:rules
# Deploy everything
firebase deploynextjs-firebase-ai-coding-template/
βββ front/ # Next.js Frontend
β βββ src/
β β βββ app/ # Next.js app router pages
β β β βββ layout.tsx # Root layout
β β β βββ page.tsx # Home page
β β β βββ signin/ # Sign in page
β β β βββ signup/ # Sign up page
β β β βββ dashboard/ # Protected dashboard
β β βββ auth/ # Authentication logic
β β β βββ authContext.ts # Auth context definition
β β β βββ authOperations.ts # Auth functions
β β β βββ AuthProvider.tsx # Auth context provider
β β β βββ useAuth.ts # Auth hook
β β βββ lib/ # Firebase services
β β β βββ firebase.ts # Firebase initialization
β β β βββ firestore.ts # Firestore operations
β β β βββ functions.ts # Cloud Functions
β β β βββ storage.ts # Storage operations
β β βββ theme/ # MUI theme configuration
β β βββ config.ts # App configuration
β βββ .env.example # Environment variables template
β βββ package.json
β βββ FRONTEND_RULES.md # Frontend-specific AI rules
βββ back/ # Python Firebase Functions Backend
β βββ main.py # Firebase function exports
β βββ run_tests.py # Test runner with emulator management
β βββ requirements.txt # Python dependencies
β βββ pytest.ini # Pytest configuration
β βββ .env.example # Backend environment template
β βββ BACKEND_RULES.md # Backend-specific AI rules
β βββ ADR.md # Architecture Decision Records
β βββ src/
β β βββ apis/ # Database interfaces and API clients
β β β βββ Db.py # Database singleton
β β βββ brokers/ # Firebase function handlers
β β β βββ callable/ # Client-callable functions
β β β βββ https/ # HTTP endpoints
β β β βββ triggered/ # Event-triggered functions
β β βββ documents/ # Firestore document classes
β β β βββ DocumentBase.py # Base document class
β β β βββ [collections]/ # Collection-specific classes
β β βββ models/ # Data models and types
β β β βββ firestore_types.py # Firestore document types
β β β βββ function_types.py # Function request/response types
β β β βββ util_types.py # Utility types
β β βββ services/ # Business logic services
β β βββ util/ # Utility functions
β β βββ exceptions/ # Custom exceptions
β βββ tests/
β βββ conftest.py # Pytest fixtures
β βββ integration/ # Integration tests
β βββ unit/ # Unit tests
βββ tasks/ # AI Development Templates
β βββ PRD.md # Product Requirements Document template
β βββ TASK_TEMPLATE.md # Task breakdown template
βββ AGENTS.md # AI agent instructions
βββ firebase.json # Firebase configuration
βββ firestore.rules # Firestore security rules
βββ storage.rules # Storage security rules
βββ README.md # This file
Update firestore.rules with appropriate security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Allow users to read/write their own documents
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}Update storage.rules for file security:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /users/{userId}/{allPaths=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}# Generate PRD from requirements
# Use tasks/PRD.md template
# Ask AI to interview you until it can fill the PRD
# Break down into tasks
# Use tasks/TASK_TEMPLATE.md
# Have AI create specific, actionable tasks with dependenciesLaunch multiple AI agents (Cursor, Claude Code, etc.) in parallel:
# Agent 1: Frontend auth
@AGENTS.md @FRONTEND_RULES.md implement [task1.md]
# Agent 2: Backend API
@AGENTS.md @BACKEND_RULES.md implement [task2.md]
# Agent 3: Database models
@AGENTS.md @BACKEND_RULES.md implement [task3.md]
# Agent 4: Integration tests
@AGENTS.md implement integration tests for [feature]# Backend: Always write integration tests first
cd back
source venv/bin/activate
python run_tests.py # Tests with real APIs
# Frontend: Test with emulators
firebase emulators:start
cd front && yarn devAfter significant changes, update ADR:
# Tell agent to document decisions
"Document the key architectural decisions in back/ADR.md"cd front
yarn dev # Start development server
yarn build # Build for production
yarn lint # Run lintingcd back
source venv/bin/activate
# Run tests
python run_tests.py # All tests with emulators
python run_tests.py --test-type unit # Unit tests only
python run_tests.py --test-type integration # Integration tests only- Start Firebase emulators:
firebase emulators:start - Frontend terminal:
cd front && yarn dev - Backend terminal:
cd back && source venv/bin/activate - Make changes and test integration
import { useAuth } from "@/auth/useAuth";
import { authOperations } from "@/auth/authOperations";
// Using the auth hook
function MyComponent() {
const { user, loading, isAuthenticated } = useAuth();
if (loading) return <div>Loading...</div>;
if (!isAuthenticated) return <div>Please sign in</div>;
return <div>Welcome, {user.email}!</div>;
}
// Auth operations
await authOperations.signUp(email, password, displayName);
await authOperations.signIn(email, password);
await authOperations.signInWithGoogle();
await authOperations.signOut();import { userOperations } from "@/lib/firestore";
// Create user document
await userOperations.create(uid, { displayName, email });
// Get user by ID
const user = await userOperations.getById(uid);
// Update user
await userOperations.update(uid, { displayName: "New Name" });# src/brokers/callable/example_callable.py
from firebase_functions import https_fn, options
from src.apis.Db import Db
from src.util.db_auth_wrapper import db_auth_wrapper
@https_fn.on_call(
cors=options.CorsOptions(cors_origins=["*"]),
ingress=options.IngressSetting.ALLOW_ALL,
)
def example_callable(req: https_fn.CallableRequest):
uid = db_auth_wrapper(req)
# Implementation# src/documents/examples/Example.py
from src.documents.DocumentBase import DocumentBase
from src.apis.Db import Db
from src.models.firestore_types import ExampleDoc
class Example(DocumentBase[ExampleDoc]):
pydantic_model = ExampleDoc
def __init__(self, id: str, doc: Optional[dict] = None):
self._db = Db.get_instance()
self.collection_ref = self.db.collections["examples"]
super().__init__(id, doc)
@property
def db(self) -> Db:
if self._db is None:
self._db = Db.get_instance()
return self._db- Push your code to GitHub
- Import your repository on Vercel
- Add environment variables in Vercel dashboard
- Deploy!
cd back
firebase deploy --only functions- Update Project IDs in
back/src/apis/Db.py:
def is_prod_environment(self) -> bool:
return self.project_id in ["your-prod-project-id"]
def is_dev_environment(self) -> bool:
return self.project_id in ["your-dev-project-id"]- Deploy Security Rules:
# Review and customize rules first
cat firestore.rules
cat storage.rules
# Deploy rules
firebase deploy --only firestore:rules,storage:rules- Set Firebase Indexes (if needed):
- Check console for index requirements
- Click provided links to create indexes
- Integration First - Test real Firebase Functions, not mocks
- Error Cases First - Test failure scenarios before success
- Full Verification - Check both API responses and database state
- Use Emulators - Never mock Firebase services
- End-to-End - Test complete user workflows
When working with AI agents:
# Always tell AI to:
1. Write integration tests with real data
2. Run tests and verify they pass
3. Test with actual files/APIs, not mocks
4. Show you where to find generated outputsdef test_feature_integration(self, firebase_emulator, setup):
# Arrange - Prepare test data
test_data = {"field": "value"}
# Act - Call real Firebase Function
response = requests.post(
f"{firebase_emulator['base_url']}/function_name",
json={"data": test_data},
headers={"User-Id": setup.user_id}
)
# Assert - Verify response
assert response.status_code == 200
result = response.json()["result"]
# Assert - Verify database state
doc = DocumentClass(result["docId"])
assert doc.exists
assert doc.data.field == "value"- Database as Truth - Firestore is the single source of truth
- No Direct Responses - Backend saves to DB, frontend subscribes
- Real-time Updates - UI updates automatically via Firestore hooks
- Decoupled Design - Frontend and backend communicate through database
- DocumentBase Pattern - All Firestore operations through DocumentBase classes
- No Direct DB Calls - Always use the Db singleton
- One Class Per File - Maintain clear file organization
- Broker Pattern - Handlers stay thin, logic in services
- Pydantic Models - Define all types in models/
- Runtime Validation - Catch errors early
- Type as Documentation - Types serve as API contracts
- Parallel Agents - Run multiple agents simultaneously
- Test-Driven - AI must write and run tests
- Documentation - Update ADR after major decisions
- Real APIs - Never let AI mock critical services
cd front
yarn dev # Start development server
yarn build # Build for production
yarn start # Start production server
yarn lint # Run ESLint
yarn type-check # Run TypeScript checkscd back
python run_tests.py # Run all tests with emulators
python run_tests.py --test-type unit # Unit tests only
python run_tests.py --test-type integration # Integration tests
pytest --cov=src # Run with coverage reportfirebase emulators:start # Start local emulators
firebase deploy # Deploy everything
firebase deploy --only functions # Deploy functions only
firebase deploy --only hosting # Deploy frontend only
firebase deploy --only firestore:rules # Deploy Firestore rulesNEXT_PUBLIC_FIREBASE_API_KEY=your_api_key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_auth_domain
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your_storage_bucket
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id
NEXT_PUBLIC_FIREBASE_APP_ID=your_app_id
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=your_measurement_idBackend (back/.env):
FIREBASE_SERVICE_ACCOUNT_PATH- Path to service account JSON[YOUR_API_KEYS]- Any third-party API keys needed
Frontend (front/.env.local):
- All
NEXT_PUBLIC_FIREBASE_*variables from Firebase config - Any other public environment variables
Note: Never commit .env files or service account keys to version control!
- Create Firebase project
- Enable Authentication, Firestore, Storage, Functions
- Download service account key
- Configure environment variables
- Install dependencies (front & back)
- Start emulators
- Run tests
- Launch development servers
- Create PRD with AI
- Generate tasks from PRD
- Launch parallel AI agents
For issues and questions, please open an issue on GitHub.
Built for the AI development era with Next.js, Firebase, and Python