Logo Firebase

Firebase

Cộng đồng
Fandry96
firebase

Firebase full-stack backend: App Hosting for Next.js SSR on Cloud Run, Auth SSR with HttpOnly cookies and proxy.ts, image optimization via Extensions, Firestore/Data Connect, billing protection. Use when: Firebase project, auth, hosting, functions, storage, security rules, App Hosting, Next.js 16 SSR.

Tổng quan

Nhà phát hànhFandry96
Kho mãk3-agentic-skills
Tên kỹ năngfirebase
Sao
27
Bản fork
5
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được Fandry96 công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Firebase trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/Fandry96/k3-agentic-skills/tree/master/skills/firebase
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Fandry96/k3-agentic-skills.git /tmp/k3-agentic-skills
mkdir -p .claude/skills
cp -r /tmp/k3-agentic-skills/skills/firebase .claude/skills/firebase
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Firebase trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Firebase ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Firebase không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Firebase — Full-Stack Backend & App Hosting

You are a Firebase expert who has shipped production apps on App Hosting, Auth, Firestore, Cloud Functions, and Storage. You know the sharp edges: billing surprises, Security Rules gotchas, Turbopack incompatibilities, and the difference between Hosting Classic (static only) and App Hosting (SSR on Cloud Run).

Capabilities

  • firebase-app-hosting (Next.js SSR on Cloud Run)
  • firebase-auth (client + Admin SDK + SSR cookies)
  • firestore
  • firebase-data-connect (PostgreSQL 17 via GraphQL)
  • firebase-cloud-functions
  • firebase-storage
  • firebase-hosting-classic (static sites only)
  • firebase-security-rules
  • firebase-admin-sdk
  • firebase-emulators
  • firebase-studio (cloud IDE with Nix environments)
  • firebase-extensions (Image Processing, etc.)

Critical: Hosting Classic vs. App Hosting

FeatureHosting ClassicApp Hosting
Static HTML/CSS/JS✅✅
Next.js SSR / App Router❌✅
Server Components❌✅
ISR / Revalidation❌✅
BackendCDN onlyCloud Run containers
CLI Commandfirebase init hostingfirebase apphosting:backends:create

Rule: If the project uses Next.js App Router, you MUST use App Hosting. Hosting Classic will fail on any server-rendered routes.

App Hosting Setup

bash
# Initialize App Hosting (replaces classic hosting for SSR apps)
firebase apphosting:backends:create --project=<PROJECT_ID>
# Select region (e.g., us-east1 for East Coast US)
# Connect GitHub repo for automatic builds

firebase.json for App Hosting

json
{
  "hosting": {
    "source": ".",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

Auth SSR: The proxy.ts HttpOnly Cookie Pattern (Next.js 16)

Context: Next.js 16 deprecates Edge-based middleware.ts for auth. The new pattern uses proxy.ts with Node.js runtime for full Admin SDK compatibility.

Architecture

  1. Client signs in with Firebase Auth (client SDK)
  2. Client sends ID token to /api/session Server Action
  3. Server verifies token + sets HttpOnly __session cookie
  4. proxy.ts reads cookie on every request, injects user context via headers

/api/session/route.ts

typescript
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/firebase-admin';

export async function POST(req: NextRequest) {
  const { idToken } = await req.json();
  if (!idToken) return new Response('Missing ID token', { status: 401 });

  try {
    const expiresIn = 60 * 60 * 24 * 5 * 1000; // 5 days
    const sessionCookie = await auth.createSessionCookie(idToken, { expiresIn });
    const response = new NextResponse('Session created', { status: 200 });
    response.cookies.set('__session', sessionCookie, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: expiresIn,
      path: '/',
    });
    return response;
  } catch (error) {
    console.error('Session cookie error:', error);
    return new Response('Unauthorized', { status: 401 });
  }
}

proxy.ts — Session Verification

typescript
import { NextRequest, NextResponse } from "next/server";
import { auth } from "./lib/firebase-admin";

export async function proxy(request: NextRequest) {
  const sessionCookie = request.cookies.get("__session")?.value;
  const isProtectedRoute =
    request.nextUrl.pathname.startsWith("/portal") ||
    request.nextUrl.pathname.startsWith("/api/chat") ||
    request.nextUrl.pathname.startsWith("/api/vault");

  if (isProtectedRoute) {
    if (!sessionCookie) {
      return NextResponse.redirect(new URL("/login", request.url));
    }
    try {
      const decoded = await auth.verifySessionCookie(sessionCookie, true);
      const headers = new Headers(request.headers);
      headers.set("x-user-id", decoded.uid);
      headers.set("x-user-email", decoded.email || "");
      return NextResponse.next({ request: { headers } });
    } catch {
      const response = NextResponse.redirect(new URL("/login", request.url));
      response.cookies.delete("__session");
      return response;
    }
  }
  return NextResponse.next();
}

Next.js 16 + Turbopack Compatibility

The Problem

firebase-admin uses Node.js native modules (crypto, fs) that Turbopack's HMR cannot resolve, causing TypeError: INTERNAL during development.

Workarounds (pick one)

  1. Isolate firebase-admin — Only import it in Server Actions, API routes, or proxy.ts (never in shared/client modules)
  2. Fall back to Webpack — next dev --webpack (slower but guaranteed compatible)
  3. Sub-path imports — Use package.json imports field to alias server-only modules

Rule

NEVER import firebase-admin in a file that also has "use client" or is imported by a Client Component.

Image Optimization (Firebase Extension)

Replaces Vercel's built-in image optimization. Uses the Image Processing Firebase Extension with Cloud Functions (2M free invocations/month on Blaze).

Setup

  1. Install Image Processing Extension via Firebase Console
  2. Point at Cloud Storage bucket
  3. Create loader.js:
javascript
// loader.js — routes images through Firebase Extension
export default function firebaseImageLoader({ src, width, quality }) {
  const params = new URLSearchParams({
    url: src,
    w: width.toString(),
    q: (quality || 75).toString(),
  });
  return `/_image?${params.toString()}`;
}
  1. Update next.config.ts:
typescript
images: {
  loader: "custom",
  loaderFile: "./loader.js",
  remotePatterns: [
    { protocol: 'https', hostname: 'cdn.sanity.io' },
    // Keep remotePatterns as fallback
  ],
}

Caching with use cache (Next.js 16)

Replace manual Cache-Control headers with component-level caching.

typescript
// In a Server Component or data-fetching function
"use cache";
import { cacheLife } from "next/cache";

export async function getNeighborhoodData(slug: string) {
  cacheLife("days"); // Static data — cache for days
  // ... fetch from Sanity
}

export async function getListingPrice(id: string) {
  cacheLife("minutes"); // Dynamic data — refresh every few minutes
  // ... fetch from API
}

Cache Invalidation

typescript
import { updateTag } from "next/cache";

// In a Server Action or API route after data changes:
updateTag("listing-123"); // Immediate invalidation

Billing Protection (MANDATORY)

GCP Budget Hard Cap

Set a hard budget cap in Google Cloud Console (e.g., $300/month). The service stops at 100%.

Tiered Alerts

ThresholdAction
25%Email notification
50%Email + Slack webhook
75%Email + Slack + review usage
90%Final warning before cap
100%Service stops (hard cap)

Setup Path

Google Cloud Console → Billing → Budgets & Alerts → Create Budget


Firebase Studio (Cloud IDE)

Firebase Studio is a cloud-based IDE (Code OSS) with Nix-based reproducible environments.

dev.nix

nix
{ pkgs, ... }:
{
  channel = "stable-24.11";
  packages = [
    pkgs.nodejs_20
  ];
  env = {};
}

Key Facts

  • 30 free workspaces for Google Developer Program members
  • Up to 32 GB RAM per workspace
  • Nix ensures environment parity with production
  • Use /clear command to reset AI memory in long sessions

Firestore Patterns

Modular SDK Import

typescript
// ✅ Good — import only what you need
import { getFirestore, doc, getDoc } from "firebase/firestore";

// ❌ Bad — imports entire SDK
import firebase from "firebase/app";
import "firebase/firestore";

Security Rules — OR-Evaluated

// Rules are OR-evaluated: parent allow CANNOT be overridden by child deny
// If a parent rule allows access, all children inherit that access
match /users/{userId} {
  allow read: if request.auth != null; // This wins for ALL sub-collections
  match /private/{doc} {
    allow read: if request.auth.uid == userId; // This is additive, not restrictive
  }
}

Data Modeling for Queries

Design Firestore structure around query patterns, not relational normalization. Denormalize aggressively. Avoid sub-collections when you need cross-document queries.


Anti-Patterns

❌ Hosting Classic for SSR

Firebase Hosting Classic does NOT support Server-Side Rendering. Use App Hosting.

❌ No Security Rules

Default open rules (allow read, write: if true) are never acceptable, even in development.

❌ Client-Side Admin Operations

Never use firebase-admin in client-side code. It contains service account credentials.

❌ Listener on Large Collections

Listening to an entire collection with thousands of documents causes runaway read costs. Always limit queries with .where(), .limit(), or pagination.

❌ Importing firebase-admin in Client Components

Turbopack will fail. Keep firebase-admin strictly in server-only files.

❌ No Budget Cap on Blaze Plan

Always set a hard budget cap in GCP Console before going to production. DDoS without a cap has caused $98K+ bills.


Related Skills

  • firebase-data-connect — PostgreSQL 17 via GraphQL for relational data
  • nextjs-app-router-patterns — PPR, Cache Components, View Transitions
  • gcp-cloud-run — Underlying runtime for App Hosting
  • frontend-design — UI patterns for portal and listings

When to Use

Use this skill for ANY Firebase integration: auth, hosting, database, storage, functions, App Hosting, image optimization, billing setup, or Next.js 16 SSR deployment.

Câu hỏi thường gặp

Kỹ năng AI Firebase làm được gì?

Firebase full-stack backend: App Hosting for Next.js SSR on Cloud Run, Auth SSR with HttpOnly cookies and proxy.ts, image optimization via Extensions, Firestore/Data Connect, billing protection. Use when: Firebase project, auth, hosting, functions, storage, security rules, App Hosting, Next.js 16 SSR.

Vì sao nên dùng Firebase trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Firebase là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Firebase trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/Fandry96/k3-agentic-skills/tree/master/skills/firebase. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Firebase?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Firebase với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Firebase với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Firebase có miễn phí không?

Kỹ năng này được Fandry96 phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇