gcp-firestore
Build real-time applications with Google Cloud Firestore. Model data with collections and documents, execute queries with composite indexes, set up real-time listeners for live updates, enable offline persistence, and write security rules for client-side access control.
Best use case
gcp-firestore is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Build real-time applications with Google Cloud Firestore. Model data with collections and documents, execute queries with composite indexes, set up real-time listeners for live updates, enable offline persistence, and write security rules for client-side access control.
Teams using gcp-firestore should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/gcp-firestore/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How gcp-firestore Compares
| Feature / Agent | gcp-firestore | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Build real-time applications with Google Cloud Firestore. Model data with collections and documents, execute queries with composite indexes, set up real-time listeners for live updates, enable offline persistence, and write security rules for client-side access control.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# GCP Firestore
Cloud Firestore is a flexible, scalable NoSQL document database. It supports real-time synchronization, offline access, and scales automatically. Available in Native mode (real-time + offline) and Datastore mode (server-only, higher throughput).
## Core Concepts
- **Document** — a record containing fields (like a JSON object), identified by ID
- **Collection** — a group of documents
- **Subcollection** — a collection nested under a document
- **Reference** — a pointer to a document or collection location
- **Real-time listener** — streams live changes to documents or queries
- **Security Rules** — declarative access control for client SDKs
## CRUD Operations
```python
# Initialize and write documents
from google.cloud import firestore
db = firestore.Client()
# Create or overwrite a document
db.collection('users').document('user-001').set({
'name': 'Alice Johnson',
'email': 'alice@example.com',
'role': 'admin',
'created_at': firestore.SERVER_TIMESTAMP
})
# Add a document with auto-generated ID
ref = db.collection('orders').add({
'user_id': 'user-001',
'items': [
{'name': 'Widget', 'qty': 2, 'price': 29.99},
{'name': 'Gadget', 'qty': 1, 'price': 49.99}
],
'total': 109.97,
'status': 'pending',
'created_at': firestore.SERVER_TIMESTAMP
})
print(f"Created order: {ref[1].id}")
```
```python
# Read a document
doc = db.collection('users').document('user-001').get()
if doc.exists:
print(f"User: {doc.to_dict()}")
```
```python
# Update specific fields (merge)
db.collection('users').document('user-001').update({
'role': 'superadmin',
'updated_at': firestore.SERVER_TIMESTAMP
})
# Update nested fields
db.collection('users').document('user-001').update({
'preferences.theme': 'dark',
'preferences.notifications': True
})
```
```python
# Delete a document
db.collection('users').document('user-001').delete()
# Delete a specific field
db.collection('users').document('user-001').update({
'temporary_field': firestore.DELETE_FIELD
})
```
## Queries
```python
# Simple queries
users_ref = db.collection('users')
# Filter by field
admins = users_ref.where('role', '==', 'admin').stream()
# Multiple conditions
recent_orders = db.collection('orders') \
.where('status', '==', 'pending') \
.where('total', '>=', 50) \
.order_by('total', direction=firestore.Query.DESCENDING) \
.limit(20) \
.stream()
for order in recent_orders:
print(f"{order.id}: ${order.to_dict()['total']}")
```
```python
# Pagination with cursors
first_page = db.collection('orders') \
.order_by('created_at', direction=firestore.Query.DESCENDING) \
.limit(25) \
.get()
# Get next page starting after last document
last_doc = first_page[-1]
next_page = db.collection('orders') \
.order_by('created_at', direction=firestore.Query.DESCENDING) \
.start_after(last_doc) \
.limit(25) \
.get()
```
```python
# Array and IN queries
# Find users with a specific tag
db.collection('users').where('tags', 'array_contains', 'premium').stream()
# Find orders with specific statuses
db.collection('orders').where('status', 'in', ['pending', 'processing']).stream()
```
## Real-Time Listeners
```javascript
// real-time-listener.js — listen for live document changes
const { Firestore } = require('@google-cloud/firestore');
const db = new Firestore();
// Listen to a single document
const unsubscribe = db.collection('orders').doc('order-001')
.onSnapshot((doc) => {
if (doc.exists) {
console.log('Order updated:', doc.data());
}
});
// Listen to a query (all pending orders)
const queryUnsubscribe = db.collection('orders')
.where('status', '==', 'pending')
.onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
console.log('New order:', change.doc.data());
} else if (change.type === 'modified') {
console.log('Updated order:', change.doc.data());
} else if (change.type === 'removed') {
console.log('Removed order:', change.doc.id);
}
});
});
// Stop listening
// unsubscribe();
```
## Batch Writes and Transactions
```python
# Batch write (up to 500 operations)
batch = db.batch()
for i in range(100):
ref = db.collection('products').document(f'product-{i:04d}')
batch.set(ref, {
'name': f'Product {i}',
'price': round(9.99 + i * 0.5, 2),
'in_stock': True
})
batch.commit()
print("Batch write complete")
```
```python
# Transaction for atomic read-modify-write
@firestore.transactional
def transfer_funds(transaction, from_ref, to_ref, amount):
from_doc = from_ref.get(transaction=transaction)
to_doc = to_ref.get(transaction=transaction)
from_balance = from_doc.get('balance')
if from_balance < amount:
raise ValueError('Insufficient funds')
transaction.update(from_ref, {'balance': from_balance - amount})
transaction.update(to_ref, {'balance': to_doc.get('balance') + amount})
transaction = db.transaction()
transfer_funds(
transaction,
db.collection('accounts').document('alice'),
db.collection('accounts').document('bob'),
50.00
)
```
## Security Rules
```javascript
// firestore.rules — access control for client SDKs
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Users can read/write their own profile
match /users/{userId} {
allow read: if request.auth != null;
allow write: if request.auth.uid == userId;
}
// Orders: owner can read, only server can write
match /orders/{orderId} {
allow read: if request.auth.uid == resource.data.user_id;
allow create: if request.auth != null
&& request.resource.data.user_id == request.auth.uid
&& request.resource.data.total > 0;
allow update, delete: if false; // server-side only
}
// Public read, admin write
match /products/{productId} {
allow read: if true;
allow write: if request.auth.token.admin == true;
}
}
}
```
```bash
# Deploy security rules
firebase deploy --only firestore:rules
```
## Indexes
```json
// firestore.indexes.json — composite indexes for complex queries
{
"indexes": [
{
"collectionGroup": "orders",
"queryScope": "COLLECTION",
"fields": [
{"fieldPath": "status", "order": "ASCENDING"},
{"fieldPath": "total", "order": "DESCENDING"}
]
},
{
"collectionGroup": "orders",
"queryScope": "COLLECTION",
"fields": [
{"fieldPath": "user_id", "order": "ASCENDING"},
{"fieldPath": "created_at", "order": "DESCENDING"}
]
}
]
}
```
```bash
# Deploy indexes
firebase deploy --only firestore:indexes
```
## Best Practices
- Design data around your queries — denormalize for read performance
- Use subcollections for large lists that are always accessed per parent
- Keep documents small (<1MB); use subcollections for unbounded lists
- Use transactions for operations that need atomicity across documents
- Create composite indexes for queries with multiple where/orderBy clauses
- Use security rules for all client-accessible data — never trust the client
- Use batch writes for bulk operations (up to 500 per batch)
- Enable offline persistence for mobile apps with poor connectivityRelated Skills
zustand
You are an expert in Zustand, the small, fast, and scalable state management library for React. You help developers manage global state without boilerplate using Zustand's hook-based stores, selectors for performance, middleware (persist, devtools, immer), computed values, and async actions — replacing Redux complexity with a simple, un-opinionated API in under 1KB.
zoho
Integrate and automate Zoho products. Use when a user asks to work with Zoho CRM, Zoho Books, Zoho Desk, Zoho Projects, Zoho Mail, or Zoho Creator, build custom integrations via Zoho APIs, automate workflows with Deluge scripting, sync data between Zoho apps and external systems, manage leads and deals, automate invoicing, build custom Zoho Creator apps, set up webhooks, or manage Zoho organization settings. Covers Zoho CRM, Books, Desk, Projects, Creator, and cross-product integrations.
zod
You are an expert in Zod, the TypeScript-first schema declaration and validation library. You help developers define schemas that validate data at runtime AND infer TypeScript types at compile time — eliminating the need to write types and validators separately. Used for API input validation, form validation, environment variables, config files, and any data boundary.
zipkin
Deploy and configure Zipkin for distributed tracing and request flow visualization. Use when a user needs to set up trace collection, instrument Java/Spring or other services with Zipkin, analyze service dependencies, or configure storage backends for trace data.
zig
Expert guidance for Zig, the systems programming language focused on performance, safety, and readability. Helps developers write high-performance code with compile-time evaluation, seamless C interop, no hidden control flow, and no garbage collector. Zig is used for game engines, operating systems, networking, and as a C/C++ replacement.
zed
Expert guidance for Zed, the high-performance code editor built in Rust with native collaboration, AI integration, and GPU-accelerated rendering. Helps developers configure Zed, create custom extensions, set up collaborative editing sessions, and integrate AI assistants for productive coding.
zeabur
Expert guidance for Zeabur, the cloud deployment platform that auto-detects frameworks, builds and deploys applications with zero configuration, and provides managed services like databases and message queues. Helps developers deploy full-stack applications with automatic scaling and one-click marketplace services.
zapier
Automate workflows between apps with Zapier. Use when a user asks to connect apps without code, automate repetitive tasks, sync data between services, or build no-code integrations between SaaS tools.
zabbix
Configure Zabbix for enterprise infrastructure monitoring with templates, triggers, discovery rules, and dashboards. Use when a user needs to set up Zabbix server, configure host monitoring, create custom templates, define trigger expressions, or automate host discovery and registration.
yup
Validate data with Yup schemas. Use when adding form validation, defining API request schemas, validating configuration, or building type-safe validation pipelines in JavaScript/TypeScript.
yt-dlp
Download video and audio from YouTube and other platforms with yt-dlp. Use when a user asks to download YouTube videos, extract audio from videos, download playlists, get subtitles, download specific formats or qualities, batch download, archive channels, extract metadata, embed thumbnails, download from social media platforms (Twitter, Instagram, TikTok), or build media ingestion pipelines. Covers format selection, audio extraction, playlists, subtitles, metadata, and automation.
youtube-transcription
Transcribe YouTube videos to text using OpenAI Whisper and yt-dlp. Use when the user wants to get a transcript from a YouTube video, generate subtitles, convert video speech to text, create SRT/VTT captions, or extract spoken content from YouTube URLs.