firebase
Expert guidance for Firebase, Google's platform for building and scaling web and mobile applications. Helps developers set up authentication, Firestore/Realtime Database, Cloud Functions, hosting, storage, and analytics using Firebase's SDK and CLI.
What this skill does
# Firebase — Google's Backend-as-a-Service
## Overview
Firebase, Google's platform for building and scaling web and mobile applications. Helps developers set up authentication, Firestore/Realtime Database, Cloud Functions, hosting, storage, and analytics using Firebase's SDK and CLI.
## Instructions
### Project Setup
```bash
# Install Firebase CLI
npm install -g firebase-tools
# Login and initialize
firebase login
firebase init
# Select: Firestore, Functions, Hosting, Storage, Emulators
# Start local development with emulators
firebase emulators:start
```
For agent-driven Firebase work, install Google's official Firebase agent skills bundle — keeps patterns current with Firebase product changes:
```bash
npx -y skills add firebase/agent-skills -y
```
Set the active project for the CLI before running commands:
```bash
npx -y firebase-tools@latest use --add <PROJECT_ID>
```
### Authentication
```typescript
// src/lib/auth.ts — Firebase Authentication
import { initializeApp } from "firebase/app";
import {
getAuth, signInWithPopup, GoogleAuthProvider, signInWithEmailAndPassword,
createUserWithEmailAndPassword, onAuthStateChanged, signOut, User
} from "firebase/auth";
const app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
});
const auth = getAuth(app);
// Google sign-in
export async function signInWithGoogle() {
const provider = new GoogleAuthProvider();
provider.addScope("email");
const result = await signInWithPopup(auth, provider);
return result.user;
}
// Email/password sign-up
export async function signUp(email: string, password: string) {
const result = await createUserWithEmailAndPassword(auth, email, password);
return result.user;
}
// Email/password sign-in
export async function signIn(email: string, password: string) {
const result = await signInWithEmailAndPassword(auth, email, password);
return result.user;
}
// Auth state listener
export function onAuth(callback: (user: User | null) => void) {
return onAuthStateChanged(auth, callback);
}
export async function logout() {
await signOut(auth);
}
```
### Firestore (Document Database)
```typescript
// src/lib/firestore.ts — Firestore CRUD operations
import {
getFirestore, collection, doc, addDoc, getDoc, getDocs,
updateDoc, deleteDoc, query, where, orderBy, limit,
onSnapshot, serverTimestamp, writeBatch, Timestamp
} from "firebase/firestore";
const db = getFirestore();
// Create a document
async function createPost(userId: string, data: { title: string; content: string }) {
const ref = await addDoc(collection(db, "posts"), {
...data,
authorId: userId,
createdAt: serverTimestamp(),
likes: 0,
published: false,
});
return ref.id;
}
// Read a document
async function getPost(postId: string) {
const snap = await getDoc(doc(db, "posts", postId));
if (!snap.exists()) throw new Error("Post not found");
return { id: snap.id, ...snap.data() };
}
// Query documents
async function getPublishedPosts(limitCount = 20) {
const q = query(
collection(db, "posts"),
where("published", "==", true),
orderBy("createdAt", "desc"),
limit(limitCount)
);
const snap = await getDocs(q);
return snap.docs.map(d => ({ id: d.id, ...d.data() }));
}
// Real-time listener
function onPostsChange(callback: (posts: any[]) => void) {
const q = query(collection(db, "posts"), where("published", "==", true), orderBy("createdAt", "desc"));
return onSnapshot(q, (snapshot) => {
const posts = snapshot.docs.map(d => ({ id: d.id, ...d.data() }));
callback(posts);
});
}
// Batch writes (atomic)
async function publishMultiplePosts(postIds: string[]) {
const batch = writeBatch(db);
for (const id of postIds) {
batch.update(doc(db, "posts", id), {
published: true,
publishedAt: serverTimestamp(),
});
}
await batch.commit();
}
```
### Security Rules
```javascript
// firestore.rules — Firestore security rules
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;
}
// Posts: anyone can read published, only author can write
match /posts/{postId} {
allow read: if resource.data.published == true
|| request.auth.uid == resource.data.authorId;
allow create: if request.auth != null
&& request.resource.data.authorId == request.auth.uid;
allow update: if request.auth.uid == resource.data.authorId;
allow delete: if request.auth.uid == resource.data.authorId;
}
}
}
```
### Cloud Functions
```typescript
// functions/src/index.ts — Serverless backend logic
import { onDocumentCreated } from "firebase-functions/v2/firestore";
import { onCall, HttpsError } from "firebase-functions/v2/https";
import { onSchedule } from "firebase-functions/v2/scheduler";
import { getFirestore } from "firebase-admin/firestore";
import { initializeApp } from "firebase-admin/app";
initializeApp();
const db = getFirestore();
// Trigger on new post creation
export const onPostCreated = onDocumentCreated("posts/{postId}", async (event) => {
const post = event.data?.data();
if (!post) return;
// Update user's post count
await db.doc(`users/${post.authorId}`).update({
postCount: FieldValue.increment(1),
});
// Send notification
await sendNotification(post.authorId, `Your post "${post.title}" was created!`);
});
// Callable function (client calls directly)
export const likePost = onCall(async (request) => {
if (!request.auth) throw new HttpsError("unauthenticated", "Must be logged in");
const { postId } = request.data;
const postRef = db.doc(`posts/${postId}`);
await db.runTransaction(async (tx) => {
const post = await tx.get(postRef);
if (!post.exists) throw new HttpsError("not-found", "Post not found");
tx.update(postRef, { likes: (post.data()!.likes || 0) + 1 });
tx.set(db.doc(`posts/${postId}/likes/${request.auth!.uid}`), {
createdAt: new Date(),
});
});
return { success: true };
});
// Scheduled function (cron)
export const dailyCleanup = onSchedule("every day 03:00", async () => {
const cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const oldDrafts = await db.collection("posts")
.where("published", "==", false)
.where("createdAt", "<", cutoff)
.get();
const batch = db.batch();
oldDrafts.docs.forEach(doc => batch.delete(doc.ref));
await batch.commit();
console.log(`Deleted ${oldDrafts.size} old drafts`);
});
```
### Storage
```typescript
// Upload and manage files
import { getStorage, ref, uploadBytes, getDownloadURL, deleteObject } from "firebase/storage";
const storage = getStorage();
async function uploadImage(file: File, path: string): Promise<string> {
const storageRef = ref(storage, `images/${path}/${file.name}`);
const snapshot = await uploadBytes(storageRef, file, {
contentType: file.type,
customMetadata: { uploadedBy: "user-123" },
});
return getDownloadURL(snapshot.ref);
}
```
## Installation
```bash
npm install firebase # Client SDK
npm install firebase-admin # Server/Cloud Functions SDK
npm install -g firebase-tools # CLI
```
## Examples
### Example 1: Setting up Firebase with a custom configuration
**User request:**
```
I just installed Firebase. Help me configure it for my TypeScript + React workflow with my preferred keybindings.
```
The agent creates the configuration file with TypeScript-aware settings, configures relevant plugins/extensions for React development, sets up keyboard shortcuts matching the user's preferences, and verifies the setup works correctly.
### Example 2: Extending Firebase with custom functionality
**User request:**
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.