[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-8c1971e6-5317-4936-abd4-ada928be29ec":3,"$fWtvnNy_wPa9gfAZETSWtiw12hr22ZTV2pdM7dbw4gR4":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"8c1971e6-5317-4936-abd4-ada928be29ec","firebase","Firebase在几分钟内为您提供完整的后端 - 认证、数据库、","cat_life_career","mod_other","sickn33,other","---\nname: firebase\ndescription: Firebase gives you a complete backend in minutes - auth, database,\n  storage, functions, hosting. But the ease of setup hides real complexity.\n  Security rules are your last line of defense, and they're often wrong.\nrisk: unknown\nsource: vibeship-spawner-skills (Apache 2.0)\ndate_added: 2026-02-27\n---\n\n# Firebase\n\nFirebase gives you a complete backend in minutes - auth, database, storage,\nfunctions, hosting. But the ease of setup hides real complexity. Security rules\nare your last line of defense, and they're often wrong. Firestore queries are\nlimited, and you learn this after you've designed your data model.\n\nThis skill covers Firebase Authentication, Firestore, Realtime Database, Cloud\nFunctions, Cloud Storage, and Firebase Hosting. Key insight: Firebase is\noptimized for read-heavy, denormalized data. If you're thinking relationally,\nyou're thinking wrong.\n\n2025 lesson: Firestore pricing can surprise you. Reads are cheap until they're\nnot. A poorly designed listener can cost more than a dedicated database. Plan\nyour data model for your query patterns, not your data relationships.\n\n## Principles\n\n- Design data for queries, not relationships\n- Security rules are mandatory, not optional\n- Denormalize aggressively - duplication is cheap, joins are expensive\n- Batch writes and transactions for consistency\n- Use offline persistence wisely - it's not free\n- Cloud Functions for what clients shouldn't do\n- Environment-based config, never hardcode keys in client\n\n## Capabilities\n\n- firebase-auth\n- firestore\n- firebase-realtime-database\n- firebase-cloud-functions\n- firebase-storage\n- firebase-hosting\n- firebase-security-rules\n- firebase-admin-sdk\n- firebase-emulators\n\n## Scope\n\n- general-backend-architecture -> backend\n- payment-processing -> stripe\n- email-sending -> email\n- advanced-auth-flows -> authentication-oauth\n- kubernetes-deployment -> devops\n\n## Tooling\n\n### Core\n\n- firebase - When: Client-side SDK Note: Modular SDK - tree-shakeable\n- firebase-admin - When: Server-side \u002F Cloud Functions Note: Full access, bypasses security rules\n- firebase-functions - When: Cloud Functions v2 Note: v2 functions are recommended\n\n### Testing\n\n- @firebase\u002Frules-unit-testing - When: Testing security rules Note: Essential - rules bugs are security bugs\n- firebase-tools - When: Emulator suite Note: Local development without hitting production\n\n### Frameworks\n\n- reactfire - When: React + Firebase Note: Hooks-based, handles subscriptions\n- vuefire - When: Vue + Firebase Note: Vue-specific bindings\n- angularfire - When: Angular + Firebase Note: Official Angular bindings\n\n## Patterns\n\n### Modular SDK Import\n\nImport only what you need for smaller bundles\n\n**When to use**: Client-side Firebase usage\n\n# MODULAR IMPORTS:\n\n\"\"\"\nFirebase v9+ uses modular SDK. Import only what you need.\nThis enables tree-shaking and smaller bundles.\n\"\"\"\n\n\u002F\u002F WRONG: v8-compat style (larger bundle)\nimport firebase from 'firebase\u002Fcompat\u002Fapp';\nimport 'firebase\u002Fcompat\u002Ffirestore';\nconst db = firebase.firestore();\n\n\u002F\u002F RIGHT: v9+ modular (tree-shakeable)\nimport { initializeApp } from 'firebase\u002Fapp';\nimport { getFirestore, collection, doc, getDoc } from 'firebase\u002Ffirestore';\n\nconst app = initializeApp(firebaseConfig);\nconst db = getFirestore(app);\n\n\u002F\u002F Get a document\nconst docRef = doc(db, 'users', 'userId');\nconst docSnap = await getDoc(docRef);\n\nif (docSnap.exists()) {\n  console.log(docSnap.data());\n}\n\n\u002F\u002F Query with constraints\nimport { query, where, orderBy, limit } from 'firebase\u002Ffirestore';\n\nconst q = query(\n  collection(db, 'posts'),\n  where('published', '==', true),\n  orderBy('createdAt', 'desc'),\n  limit(10)\n);\n\n### Security Rules Design\n\nSecure your data with proper rules from day one\n\n**When to use**: Any Firestore database\n\n# FIRESTORE SECURITY RULES:\n\n\"\"\"\nRules are your last line of defense. Every read and write\ngoes through them. Get them wrong, and your data is exposed.\n\"\"\"\n\nrules_version = '2';\nservice cloud.firestore {\n  match \u002Fdatabases\u002F{database}\u002Fdocuments {\n\n    \u002F\u002F Helper functions\n    function isSignedIn() {\n      return request.auth != null;\n    }\n\n    function isOwner(userId) {\n      return request.auth.uid == userId;\n    }\n\n    function isAdmin() {\n      return request.auth.token.admin == true;\n    }\n\n    \u002F\u002F Users collection\n    match \u002Fusers\u002F{userId} {\n      \u002F\u002F Anyone can read public profile\n      allow read: if true;\n\n      \u002F\u002F Only owner can write their own data\n      allow write: if isOwner(userId);\n\n      \u002F\u002F Private subcollection\n      match \u002Fprivate\u002F{document=**} {\n        allow read, write: if isOwner(userId);\n      }\n    }\n\n    \u002F\u002F Posts collection\n    match \u002Fposts\u002F{postId} {\n      \u002F\u002F Anyone can read published posts\n      allow read: if resource.data.published == true\n                  || isOwner(resource.data.authorId);\n\n      \u002F\u002F Only authenticated users can create\n      allow create: if isSignedIn()\n                    && request.resource.data.authorId == request.auth.uid;\n\n      \u002F\u002F Only author can update\u002Fdelete\n      allow update, delete: if isOwner(resource.data.authorId);\n    }\n\n    \u002F\u002F Admin-only collection\n    match \u002Fadmin\u002F{document=**} {\n      allow read, write: if isAdmin();\n    }\n  }\n}\n\n### Data Modeling for Queries\n\nDesign Firestore data structure around query patterns\n\n**When to use**: Designing Firestore schema\n\n# FIRESTORE DATA MODELING:\n\n\"\"\"\nFirestore is NOT relational. You can't JOIN.\nDesign your data for how you'll QUERY it, not how it relates.\n\"\"\"\n\n\u002F\u002F WRONG: Normalized (SQL thinking)\n\u002F\u002F users\u002F{userId}\n\u002F\u002F posts\u002F{postId} with authorId field\n\u002F\u002F To get \"posts by user\" - need to query posts collection\n\n\u002F\u002F RIGHT: Denormalized for queries\n\u002F\u002F users\u002F{userId}\u002Fposts\u002F{postId} - subcollection\n\u002F\u002F OR\n\u002F\u002F posts\u002F{postId} with embedded author data\n\n\u002F\u002F Document structure for a post\nconst post = {\n  id: 'post123',\n  title: 'My Post',\n  content: '...',\n\n  \u002F\u002F Embed frequently-needed author data\n  author: {\n    id: 'user456',\n    name: 'Jane Doe',\n    avatarUrl: '...'\n  },\n\n  \u002F\u002F Arrays for IN queries (max 30 items for 'in')\n  tags: ['javascript', 'firebase'],\n\n  \u002F\u002F Maps for compound queries\n  stats: {\n    likes: 42,\n    comments: 7,\n    views: 1000\n  },\n\n  \u002F\u002F Timestamps\n  createdAt: serverTimestamp(),\n  updatedAt: serverTimestamp(),\n\n  \u002F\u002F Booleans for filtering\n  published: true,\n  featured: false\n};\n\n\u002F\u002F Query patterns this enables:\n\u002F\u002F - Get post with author info: 1 read (no join needed)\n\u002F\u002F - Posts by tag: where('tags', 'array-contains', 'javascript')\n\u002F\u002F - Featured posts: where('featured', '==', true)\n\u002F\u002F - Recent posts: orderBy('createdAt', 'desc')\n\n\u002F\u002F When author updates their name, update all their posts\n\u002F\u002F This is the tradeoff: writes are more complex, reads are fast\n\n### Real-time Listeners\n\nSubscribe to data changes with proper cleanup\n\n**When to use**: Real-time features\n\n# REAL-TIME LISTENERS:\n\n\"\"\"\nonSnapshot creates a persistent connection. Always unsubscribe\nwhen component unmounts to prevent memory leaks and extra reads.\n\"\"\"\n\n\u002F\u002F React hook for real-time document\nfunction useDocument(path) {\n  const [data, setData] = useState(null);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    const docRef = doc(db, path);\n\n    \u002F\u002F Subscribe to document\n    const unsubscribe = onSnapshot(\n      docRef,\n      (snapshot) => {\n        if (snapshot.exists()) {\n          setData({ id: snapshot.id, ...snapshot.data() });\n        } else {\n          setData(null);\n        }\n        setLoading(false);\n      },\n      (err) => {\n        setError(err);\n        setLoading(false);\n      }\n    );\n\n    \u002F\u002F Cleanup on unmount\n    return () => unsubscribe();\n  }, [path]);\n\n  return { data, loading, error };\n}\n\n\u002F\u002F Usage\nfunction UserProfile({ userId }) {\n  const { data: user, loading } = useDocument(`users\u002F${userId}`);\n\n  if (loading) return \u003CSpinner \u002F>;\n  return \u003Cdiv>{user?.name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Collection with query\nfunction usePosts(limit = 10) {\n  const [posts, setPosts] = useState([]);\n\n  useEffect(() => {\n    const q = query(\n      collection(db, 'posts'),\n      where('published', '==', true),\n      orderBy('createdAt', 'desc'),\n      limit(limit)\n    );\n\n    const unsubscribe = onSnapshot(q, (snapshot) => {\n      const results = snapshot.docs.map(doc => ({\n        id: doc.id,\n        ...doc.data()\n      }));\n      setPosts(results);\n    });\n\n    return () => unsubscribe();\n  }, [limit]);\n\n  return posts;\n}\n\n### Cloud Functions Patterns\n\nServer-side logic with Cloud Functions v2\n\n**When to use**: Backend logic, triggers, scheduled tasks\n\n# CLOUD FUNCTIONS V2:\n\n\"\"\"\nCloud Functions run server-side code triggered by events.\nV2 uses more standard Node.js patterns and better scaling.\n\"\"\"\n\nimport { onRequest } from 'firebase-functions\u002Fv2\u002Fhttps';\nimport { onDocumentCreated } from 'firebase-functions\u002Fv2\u002Ffirestore';\nimport { onSchedule } from 'firebase-functions\u002Fv2\u002Fscheduler';\nimport { getFirestore } from 'firebase-admin\u002Ffirestore';\nimport { initializeApp } from 'firebase-admin\u002Fapp';\n\ninitializeApp();\nconst db = getFirestore();\n\n\u002F\u002F HTTP function\nexport const api = onRequest(\n  { cors: true, region: 'us-central1' },\n  async (req, res) => {\n    \u002F\u002F Verify auth token\n    const token = req.headers.authorization?.split('Bearer ')[1];\n    if (!token) {\n      res.status(401).json({ error: 'Unauthorized' });\n      return;\n    }\n\n    try {\n      const decoded = await getAuth().verifyIdToken(token);\n      \u002F\u002F Process request with decoded.uid\n      res.json({ userId: decoded.uid });\n    } catch (error) {\n      res.status(401).json({ error: 'Invalid token' });\n    }\n  }\n);\n\n\u002F\u002F Firestore trigger - on document create\nexport const onUserCreated = onDocumentCreated(\n  'users\u002F{userId}',\n  async (event) => {\n    const snapshot = event.data;\n    const userId = event.params.userId;\n\n    if (!snapshot) return;\n\n    const userData = snapshot.data();\n\n    \u002F\u002F Send welcome email, create related documents, etc.\n    await db.collection('notifications').add({\n      userId,\n      type: 'welcome',\n      message: `Welcome, ${userData.name}!`,\n      createdAt: FieldValue.serverTimestamp()\n    });\n  }\n);\n\n\u002F\u002F Scheduled function (every day at midnight)\nexport const dailyCleanup = onSchedule(\n  { schedule: '0 0 * * *', timeZone: 'UTC' },\n  async (event) => {\n    const cutoff = new Date();\n    cutoff.setDate(cutoff.getDate() - 30);\n\n    \u002F\u002F Delete old documents\n    const oldDocs = await db.collection('logs')\n      .where('createdAt', '\u003C', cutoff)\n      .limit(500)\n      .get();\n\n    const batch = db.batch();\n    oldDocs.docs.forEach(doc => batch.delete(doc.ref));\n    await batch.commit();\n\n    console.log(`Deleted ${oldDocs.size} old logs`);\n  }\n);\n\n### Batch Operations\n\nAtomic writes and transactions for consistency\n\n**When to use**: Multiple document updates that must succeed together\n\n# BATCH WRITES AND TRANSACTIONS:\n\n\"\"\"\nBatches: Multiple writes that all succeed or all fail.\nTransactions: Read-then-write operations with consistency.\nMax 500 operations per batch\u002Ftransaction.\n\"\"\"\n\nimport {\n  writeBatch, runTransaction, doc, getDoc,\n  increment, serverTimestamp\n} from 'firebase\u002Ffirestore';\n\n\u002F\u002F Batch write - no reads, just writes\nasync function createPostWithTags(post, tags) {\n  const batch = writeBatch(db);\n\n  \u002F\u002F Create post\n  const postRef = doc(collection(db, 'posts'));\n  batch.set(postRef, {\n    ...post,\n    createdAt: serverTimestamp()\n  });\n\n  \u002F\u002F Update tag counts\n  for (const tag of tags) {\n    const tagRef = doc(db, 'tags', tag);\n    batch.set(tagRef, {\n      count: increment(1),\n      lastUsed: serverTimestamp()\n    }, { merge: true });\n  }\n\n  await batch.commit();\n  return postRef.id;\n}\n\n\u002F\u002F Transaction - read and write atomically\nasync function likePost(postId, userId) {\n  return runTransaction(db, async (transaction) => {\n    const postRef = doc(db, 'posts', postId);\n    const likeRef = doc(db, 'posts', postId, 'likes', userId);\n\n    const postSnap = await transaction.get(postRef);\n    if (!postSnap.exists()) {\n      throw new Error('Post not found');\n    }\n\n    const likeSnap = await transaction.get(likeRef);\n    if (likeSnap.exists()) {\n      throw new Error('Already liked');\n    }\n\n    \u002F\u002F Increment like count and add like document\n    transaction.update(postRef, {\n      likeCount: increment(1)\n    });\n\n    transaction.set(likeRef, {\n      userId,\n      createdAt: serverTimestamp()\n    });\n\n    return postSnap.data().likeCount + 1;\n  });\n}\n\n### Social Login (Google, GitHub, etc.)\n\nOAuth provider setup and authentication flows\n\n**When to use**: Social login implementation\n\n# SOCIAL LOGIN WITH FIREBASE AUTH\n\nimport {\n  getAuth, signInWithPopup, signInWithRedirect,\n  GoogleAuthProvider, GithubAuthProvider, OAuthProvider\n} from \"firebase\u002Fauth\";\n\nconst auth = getAuth();\n\n\u002F\u002F GOOGLE\nconst googleProvider = new GoogleAuthProvider();\ngoogleProvider.addScope(\"email\");\ngoogleProvider.setCustomParameters({ prompt: \"select_account\" });\n\nasync function signInWithGoogle() {\n  try {\n    const result = await signInWithPopup(auth, googleProvider);\n    return result.user;\n  } catch (error) {\n    if (error.code === \"auth\u002Faccount-exists-with-different-credential\") {\n      return handleAccountConflict(error);\n    }\n    throw error;\n  }\n}\n\n\u002F\u002F GITHUB\nconst githubProvider = new GithubAuthProvider();\ngithubProvider.addScope(\"read:user\");\n\n\u002F\u002F APPLE (Required for iOS apps!)\nconst appleProvider = new OAuthProvider(\"apple.com\");\nappleProvider.addScope(\"email\");\nappleProvider.addScope(\"name\");\n\n### Popup vs Redirect Auth\n\nWhen to use popup vs redirect for OAuth\n\n**When to use**: Choosing authentication flow\n\n# Popup: Desktop, SPA (simpler, can be blocked)\n# Redirect: Mobile, iOS Safari (always works)\n\nasync function signIn(provider) {\n  if (\u002FiPhone|iPad|Android\u002Fi.test(navigator.userAgent)) {\n    return signInWithRedirect(auth, provider);\n  }\n  try {\n    return await signInWithPopup(auth, provider);\n  } catch (e) {\n    if (e.code === \"auth\u002Fpopup-blocked\") {\n      return signInWithRedirect(auth, provider);\n    }\n    throw e;\n  }\n}\n\n\u002F\u002F Check redirect result on page load\nuseEffect(() => {\n  getRedirectResult(auth).then(r => r && setUser(r.user));\n}, []);\n\n### Account Linking\n\nLink multiple providers to one account\n\n**When to use**: User has accounts with different providers\n\nimport { fetchSignInMethodsForEmail, linkWithCredential } from \"firebase\u002Fauth\";\n\nasync function handleAccountConflict(error) {\n  const email = error.customData?.email;\n  const pendingCred = OAuthProvider.credentialFromError(error);\n  const methods = await fetchSignInMethodsForEmail(auth, email);\n\n  if (methods.includes(\"google.com\")) {\n    alert(\"Sign in with Google to link accounts\");\n    const result = await signInWithPopup(auth, new GoogleAuthProvider());\n    await linkWithCredential(result.user, pendingCred);\n    return result.user;\n  }\n}\n\n\u002F\u002F Link new provider\nawait linkWithPopup(auth.currentUser, new GithubAuthProvider());\n\n\u002F\u002F Unlink provider (keep at least one!)\nawait unlink(auth.currentUser, \"github.com\");\n\n### Auth State Persistence\n\nControl session lifetime\n\n**When to use**: Managing user sessions\n\nimport { setPersistence, browserLocalPersistence, browserSessionPersistence } from \"firebase\u002Fauth\";\n\n\u002F\u002F LOCAL: survives browser close (default)\n\u002F\u002F SESSION: cleared on tab close\n\nasync function signInWithRememberMe(email, pass, remember) {\n  await setPersistence(auth, remember ? browserLocalPersistence : browserSessionPersistence);\n  return signInWithEmailAndPassword(auth, email, pass);\n}\n\n\u002F\u002F React auth hook\nfunction useAuth() {\n  const [user, setUser] = useState(null);\n  const [loading, setLoading] = useState(true);\n  useEffect(() => onAuthStateChanged(auth, u => { setUser(u); setLoading(false); }), []);\n  return { user, loading };\n}\n\n### Email Verification and Password Reset\n\nComplete email auth flow\n\n**When to use**: Email\u002Fpassword authentication\n\nimport { sendEmailVerification, sendPasswordResetEmail, reauthenticateWithCredential } from \"firebase\u002Fauth\";\n\n\u002F\u002F Sign up with verification\nasync function signUp(email, password) {\n  const result = await createUserWithEmailAndPassword(auth, email, password);\n  await sendEmailVerification(result.user);\n  return result.user;\n}\n\n\u002F\u002F Password reset\nawait sendPasswordResetEmail(auth, email);\n\n\u002F\u002F Change password (requires recent auth)\nconst cred = EmailAuthProvider.credential(user.email, currentPass);\nawait reauthenticateWithCredential(user, cred);\nawait updatePassword(user, newPass);\n\n### Token Management for APIs\n\nHandle ID tokens for backend calls\n\n**When to use**: Authenticating with backend APIs\n\nimport { getIdToken, onIdTokenChanged } from \"firebase\u002Fauth\";\n\n\u002F\u002F Get token (auto-refreshes if expired)\nconst token = await getIdToken(auth.currentUser);\n\n\u002F\u002F API helper with auto-retry\nasync function apiCall(url, opts = {}) {\n  const token = await getIdToken(auth.currentUser);\n  const res = await fetch(url, {\n    ...opts,\n    headers: { ...opts.headers, Authorization: \"Bearer \" + token }\n  });\n  if (res.status === 401) {\n    const newToken = await getIdToken(auth.currentUser, true);\n    return fetch(url, { ...opts, headers: { ...opts.headers, Authorization: \"Bearer \" + newToken }});\n  }\n  return res;\n}\n\n\u002F\u002F Sync to cookie for SSR\nonIdTokenChanged(auth, async u => {\n  document.cookie = u ? \"__session=\" + await u.getIdToken() : \"__session=; max-age=0\";\n});\n\n\u002F\u002F Check admin claim\nconst { claims } = await auth.currentUser.getIdTokenResult();\nconst isAdmin = claims.admin === true;\n\n## Collaboration\n\n### Delegation Triggers\n\n- user needs complex OAuth flow -> authentication-oauth (Firebase Auth handles basics, complex flows need OAuth skill)\n- user needs payment integration -> stripe (Firebase + Stripe common pattern)\n- user needs email functionality -> email (Firebase doesn't include email - use SendGrid, Resend, etc.)\n- user needs container deployment -> devops (Beyond Firebase Hosting - Kubernetes, Docker)\n- user needs relational data model -> postgres-wizard (Firestore is wrong choice for highly relational data)\n- user needs full-text search -> elasticsearch-search (Firestore doesn't support full-text search - use Algolia\u002FElastic)\n\n## Related Skills\n\nWorks well with: `nextjs-app-router`, `react-patterns`, `authentication-oauth`, `stripe`\n\n## When to Use\n- User mentions or implies: firebase\n- User mentions or implies: firestore\n- User mentions or implies: firebase auth\n- User mentions or implies: cloud functions\n- User mentions or implies: firebase storage\n- User mentions or implies: realtime database\n- User mentions or implies: firebase hosting\n- User mentions or implies: firebase emulator\n- User mentions or implies: security rules\n- User mentions or implies: firebase admin\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,218,389,"2026-05-16 13:18:07",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"其他","other","mdi-page-next-outline","其他类型Skill",5,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"职场发展","career","mdi-briefcase-outline","面试准备、简历优化、职业规划",4,575,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"7534bc8f-a04f-4283-abb2-b0d1639d1bbb","1.0.0","firebase.zip",6916,"uploads\u002Fskills\u002F8c1971e6-5317-4936-abd4-ada928be29ec\u002Ffirebase.zip","b50491ee97f85aff35452b95f9025612da1d8d9a1c43fc645d7c107cfb0834ef","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":18923}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]