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-ssrIs 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:
- references/nextjs.md - For Next.js App Router (RSCs, Server Actions, Route Handlers).
- references/remix.md - For Remix (
loaderandactionfunctions). - references/angular-ssr.md - For Angular SSR
(
REQUESTtoken andTransferState). - references/token-transport.md - For
client-to-server token passing (Service Worker request interception and
onIdTokenChangedcookie sync).
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 whengetAuth(app)runs. CallinggetFirestore(app),getDatabase(app),getStorage(app),getFunctions(app), orgetDataConnect(app, connectorConfig)without first callinggetAuth(app)sends requests unauthenticated even whenauthIdTokenis supplied. - Await
auth.authStateReady():FirebaseServerAppverifies and appliesauthIdTokenasynchronously. Readingauth.currentUserbeforeawait auth.authStateReady()resolves returnsnull. - Use
releaseOnDerefsafely: Pass a request-scoped object (such as theRequestorheadersobject) soFinalizationRegistrydecrements the reference count automatically when the request ends. Coercenulltoundefined(obj ?? undefined) becauseFinalizationRegistry.registerthrowsTypeError: Invalid targetonnull(common during static prerendering). Do not mixdeleteApp(app)withreleaseOnDeref. - Token transport and ID token rules: Browsers do not attach
Authorization: Bearer <idToken>orx-firebase-appcheckheaders 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 (enforcingSameSite=LaxorStrictand CSRFOrigin/token validation on state-mutating endpoints)—see references/token-transport.md and the Firebase SSR token guide.authIdTokenonly 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 Remixactions or Next.js Server Actions /POSTRoute Handlers rather thanGETrenders.
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 asinitialUser(or viaTransferState)—never pass the rawfirebase/authUserclass instance across a serialization boundary. - Firestore
onSnapshotResume(firebase@11.10.0+): Fetch the query on the server withgetDocs()orgetDoc(), pass both plain initial data (or usequerySnapshotFromJSON) for immediate SSR HTML rendering andsnapshot.toJSON()for the client, then callonSnapshotResume(db, serializedSnapshot, ...)to resume real-time updates without re-fetching the initial snapshot. - Firebase SQL Connect
subscribe: Executeconst result = await listMovies(dc, { genre: "sci-fi" })on the server, serialize withresult.toJSON(), seed initial state fromserializedQuery.data, ensure the client[DEFAULT]FirebaseAppis initialized, and resume updates withsubscribe(serializedQuery, { onNext, onErr }).
How can the creator link this skill?
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>