skillZs
★ LIVE SKILL TAGS ★
>>> LIVE SKILLS INDEX <<<
* OPEN SOURCE *
NO LOGIN, NO TRACKING
※ REAL INSTALL DATA ※
← back to all skills
firebase/agent-skills140 installs

firebase-ssr

Guides using the Firebase JS SDK in Server-Side Rendering (SSR) environments with per-request isolation, server-to-client serialization, and client state resumption. Use when building SSR routes, loaders, actions, or server components in Next.js, Remix, Angular SSR, Nuxt, SvelteKit, or other JS server frameworks using initializeServerApp, authIdToken, appCheckToken, onSnapshotResume, or Firebase SQL Connect (aka Firebase Data Connect) subscribe. Don't use for deploying SSR apps, configuring apphosting.yaml, or managing secrets and rollouts (use firebase-app-hosting-basics), privileged backend tasks using firebase-admin, or standalone Analytics and Crashlytics setup.

How do I install this agent skill?

npx skills add https://github.com/firebase/agent-skills --skill firebase-ssr
view source ↗

Is this agent skill safe to install?

  • Gen Agent Trust Hubpass

    This skill provides architectural guidance and code examples for implementing Firebase in Server-Side Rendering (SSR) environments. It can read authentication tokens from request headers and access Firebase data services, so ensure associated service account permissions follow the principle of least privilege.

  • Socketpass

    No alerts

  • Snykpass

    Risk: LOW · No issues

What does this agent skill do?

Firebase in SSR Environments

When building universal/SSR applications, isolate Firebase app instances per request to prevent cross-request state pollution and serialize Firebase-specific data structures before crossing the server-to-client boundary.

Framework Selection Workflow

The core concepts of Firebase SSR (request isolation, serialization mappings, and client resumption) apply across JavaScript SSR frameworks, while request APIs and hydration primitives differ per framework.

Step 1: Identify the SSR framework the user is building with.

Step 2: Read the matching framework-specific reference guide before implementing Firebase integration:

Note: For unlisted frameworks (e.g., SvelteKit, Nuxt), read references/nextjs.md and adapt headers()/cookies() to that framework's per-request event/request object.


Core Principles

Regardless of the framework selected in Step 2, enforce these core principles.

1. Initializing Firebase: Avoid the Singleton

In a Node.js or worker SSR context, the standard initializeApp() singleton is shared globally across all incoming requests.

[!WARNING] DO NOT use the standard initializeApp() inside server-side code that responds to HTTP endpoints or renders pages. It causes data and authentication token leakage between concurrent users.

Instead, call initializeServerApp per request, pass releaseOnDeref for automatic garbage-collection cleanup, and initialize getAuth(app) plus await auth.authStateReady():

import { initializeServerApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

// Must be called for every incoming request handling routine
const app = initializeServerApp(firebaseConfig, {
  authIdToken: extractedToken, // Optional Firebase Auth ID token
  appCheckToken: extractedAppCheckToken, // Optional App Check token
  releaseOnDeref: requestScopedObject ?? undefined, // Coerce null to undefined
});

// Register auth-internal and wait for async token sign-in before reading
// auth.currentUser or querying authenticated Firebase services
const auth = getAuth(app);
await auth.authStateReady();

const db = getFirestore(app);

Key requirements:

  • Always initialize getAuth(app): Firebase Auth registers internal auth providers lazily when getAuth(app) runs. Calling getFirestore(app), getDatabase(app), getStorage(app), getFunctions(app), or getDataConnect(app, connectorConfig) without first calling getAuth(app) sends requests unauthenticated even when authIdToken is supplied.
  • Await auth.authStateReady(): FirebaseServerApp verifies and applies authIdToken asynchronously. Reading auth.currentUser before await auth.authStateReady() resolves returns null.
  • Use releaseOnDeref safely: Pass a request-scoped object (such as the Request or headers object) so FinalizationRegistry decrements the reference count automatically when the request ends. Coerce null to undefined (obj ?? undefined) because FinalizationRegistry.register throws TypeError: Invalid target on null (common during static prerendering). Do not mix deleteApp(app) with releaseOnDeref.
  • Token transport and ID token rules: Browsers do not attach Authorization: Bearer <idToken> or x-firebase-appcheck headers on standard page navigations. Transmit tokens either by intercepting navigation fetches in a Service Worker or by syncing a fresh Firebase Auth ID token into a cookie read on the server (enforcing SameSite=Lax or Strict and CSRF Origin/token validation on state-mutating endpoints)—see references/token-transport.md and the Firebase SSR token guide. authIdToken only accepts a recently minted Firebase Auth ID token—do not pass a Firebase Admin session cookie (createSessionCookie).

2. Firestore Serialization Requirements

Data returned from getFirestore contains non-plain prototype instances (Timestamp, DocumentReference, GeoPoint, Bytes, VectorValue) that fail serialization across RSC, Remix json(), or Angular TransferState boundaries.

Either convert non-plain fields to JSON primitives (such as .toDate().toISOString()) before returning them to the client, or use Firestore's .toJSON() / static .fromJSON() helpers (and documentSnapshotFromJSON / querySnapshotFromJSON in firebase@11.10.0+).

3. Firebase SQL Connect Request Isolation and Serialization

Unlike Firestore, Firebase SQL Connect (aka Firebase Data Connect) returns JSON-serializable primitives from its GraphQL protocol—generated query responses (response.data) do not require manual field conversion before being passed as props, loader payloads, or signals.

However, generated SQL Connect functions must be passed a DataConnect instance bound to the request-scoped FirebaseServerApp:

import { getDataConnect } from "firebase/data-connect";
import { connectorConfig, listMovies } from "@dataconnect/generated";

const dc = getDataConnect(app, connectorConfig);
const result = await listMovies(dc, { genre: "sci-fi" });

Calling listMovies({ genre: "sci-fi" }) (or listMovies()) without the dc argument falls back to the global [DEFAULT] app (getApp()), throwing No Firebase App '[DEFAULT]' has been created or leaking unauthenticated/wrong-user context. Note also that executeGraphql belongs to the privileged firebase-admin/data-connect Admin SDK (which bypasses @auth rules unless impersonate is passed), whereas user-scoped SSR uses firebase/data-connect and generated client connectors.

4. Other Firebase Products (RTDB, Storage, Functions)

Once initializeServerApp and getAuth(app) have run for the request, client SDKs for Realtime Database, Cloud Storage, Cloud Functions, and Firebase SQL Connect automatically use the request's authIdToken and appCheckToken:

  • Realtime Database: get(ref(db, "path")).then(s => s.val()) returns plain JSON-serializable values.
  • Cloud Storage: getDownloadURL(ref(storage, "path")) resolves signed URLs under the user's Storage Security Rules.
  • Cloud Functions: httpsCallable(functions, "name")(data) invokes callable functions on behalf of the requesting user. Place mutating callables in Remix actions or Next.js Server Actions / POST Route Handlers rather than GET renders.

5. Resuming Server Context in the Client

Seed initial UI state synchronously from server-rendered data and resume live listeners on the client to avoid layout shifts and duplicate initial fetches:

  • Firebase Auth Hydration: After await auth.authStateReady(), extract a plain serializable user object (e.g., { uid, email, displayName, photoURL }) and pass it as initialUser (or via TransferState)—never pass the raw firebase/auth User class instance across a serialization boundary.
  • Firestore onSnapshotResume (firebase@11.10.0+): Fetch the query on the server with getDocs() or getDoc(), pass both plain initial data (or use querySnapshotFromJSON) for immediate SSR HTML rendering and snapshot.toJSON() for the client, then call onSnapshotResume(db, serializedSnapshot, ...) to resume real-time updates without re-fetching the initial snapshot.
  • Firebase SQL Connect subscribe: Execute const result = await listMovies(dc, { genre: "sci-fi" }) on the server, serialize with result.toJSON(), seed initial state from serializedQuery.data, ensure the client [DEFAULT] FirebaseApp is initialized, and resume updates with subscribe(serializedQuery, { onNext, onErr }).

Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.

<a href="https://skillzs.dev/skills/firebase/agent-skills/firebase-ssr">View firebase-ssr on skillZs</a>