diff --git a/README.md b/README.md index f7084fbf2..6d8c455cf 100644 --- a/README.md +++ b/README.md @@ -35,10 +35,19 @@ export const appConfig: ApplicationConfig = { ```ts import { AsyncPipe } from '@angular/common'; import { Component, inject } from '@angular/core'; -import { Firestore, collectionData, collection } from '@angular/fire/firestore'; +import { Firestore, FirestoreDataConverter, collectionData, collection } from '@angular/fire/firestore'; interface Item { name: string; +} + +// Types the collection and checks every document on its way in +const itemConverter: FirestoreDataConverter = { + toFirestore: item => item, + fromFirestore: (snapshot, options) => { + const data = snapshot.data(options); + return { name: typeof data['name'] === 'string' ? data['name'] : '' }; + }, }; @Component({ @@ -56,11 +65,13 @@ interface Item { }) export class App { firestore = inject(Firestore); - itemCollection = collection(this.firestore, 'items'); - items$ = collectionData(this.itemCollection); + itemCollection = collection(this.firestore, 'items').withConverter(itemConverter); + items$ = collectionData(this.itemCollection); // Observable } ``` +The converter is what gives the read its type. `collection()` alone returns an untyped reference. See [Typed reads](docs/firestore.md#typed-reads). + ## Resources [Quickstart](docs/install-and-setup.md) - Get your first application up and running by following our quickstart guide. diff --git a/docs/app-check.md b/docs/app-check.md index 3b8bb7b9d..d49ea3d60 100644 --- a/docs/app-check.md +++ b/docs/app-check.md @@ -52,7 +52,9 @@ App Check's reCAPTCHA providers need a browser, so AngularFire skips App Check d ### Firebase requests made during server rendering -With no App Check instance on the server, requests to Firebase made while the server renders a page carry no App Check token. If you [enforce App Check](https://firebase.google.com/docs/app-check/enable-enforcement) for a Firebase product, those requests are rejected. Firebase's recommended fix is to hand a token from the browser to the server and pass it to `initializeServerApp` as `appCheckToken`, described in [Use App Check in SSR environments](https://firebase.google.com/docs/web/ssr-apps#use-app-check). +With no App Check instance on the server, requests to Firebase made while the server renders a page carry no App Check token unless the browser relays one. If you [enforce App Check](https://firebase.google.com/docs/app-check/enable-enforcement) for a Firebase product, requests without a token are rejected. The fix is to hand the browser's token to the server and build the server app with `initializeBrowserOrServerApp`, which passes it on as `appCheckToken`. [Relaying the App Check token](auth.md#relaying-the-app-check-token) in the Authentication guide walks through it. A relayed token wins over `APP_CHECK_ON_SERVER` for Firestore, which sends the server app's token whatever App Check instance the server holds. + +In development mode the server console says so once per process: "AngularFire skips App Check during server rendering, so server renders without a relayed App Check token send none", followed by the two ways to change that. ### Running App Check during server rendering diff --git a/docs/auth.md b/docs/auth.md index ca0123790..4f49170fb 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -57,7 +57,7 @@ Update the imports from `import { ... } from 'firebase/auth'` to `import { ... } ## Server-side Rendering -When Angular renders your app on the server, the server does not know which user is visiting. To render the page as that user, pass their Auth ID token to `initializeServerApp`, which gives you a Firebase app that is already signed in as them. +When Angular renders your app on the server, the server does not know which user is visiting. To render the page as that user, hand their Auth ID token to `initializeBrowserOrServerApp`, which gives you a Firebase app that is already signed in as them on the server, and the ordinary Firebase app in the browser. Getting the token to the server is your app's job. This guide keeps it in a cookie, because the browser attaches cookies to every request on its own. @@ -78,6 +78,12 @@ export const serverRoutes: ServerRoute[] = [ The rest of this guide has no effect on routes rendered any other way. +The request context that step 3 fills and step 4 reads is provided by `AngularNodeAppEngine` and `AngularAppEngine`, the engines `ng new --ssr` sets up. An app still rendering through the older `CommonEngine` has to provide it itself, on every render: + +```ts +engine.render({ ...renderOptions, providers: [{ provide: REQUEST_CONTEXT, useValue: { authIdToken } }] }) +``` + ### 2. Keep the ID token in a cookie Install [js-cookie](https://github.com/js-cookie/js-cookie): @@ -173,6 +179,8 @@ import cookieParser from 'cookie-parser'; app.use(cookieParser()); app.use((req, res, next) => { + // A page rendered for one visitor must never be served to another from a cache. + res.setHeader('Cache-Control', 'private, no-store'); angularApp .handle(req, { authIdToken: req.cookies?.__session }) .then((response) => @@ -184,26 +192,17 @@ app.use((req, res, next) => { Keep it where the generated block already was, below the block that serves static files, so real files are still served before Angular tries to render them. The rest of the file, including the part that starts the server, stays as it is. -The second argument to `handle` is what the render reads back as `REQUEST_CONTEXT`. +The second argument to `handle` is what the render reads back as `REQUEST_CONTEXT`, and `initializeBrowserOrServerApp` reads the `authIdToken` key from it. If you forget the second argument, AngularFire says so once in the server console in development mode. + +The `Cache-Control` header is not optional. A signed-in render puts that visitor's data into the HTML, so a CDN or proxy that cached the response would hand it to the next visitor. -### 4. Build the server app from the token +### 4. Build the app with `initializeBrowserOrServerApp` -In `app.config.ts`, choose the Firebase app based on where the code is running, and pass that app to every Firebase provider: +In `app.config.ts`, build the Firebase app with `initializeBrowserOrServerApp` and pass that app to every Firebase provider: ```ts -import { - ApplicationConfig, - PLATFORM_ID, - REQUEST_CONTEXT, - inject, -} from '@angular/core'; -import { isPlatformBrowser } from '@angular/common'; -import { - FirebaseApp, - initializeApp, - initializeServerApp, - provideFirebaseApp, -} from '@angular/fire/app'; +import { ApplicationConfig, inject } from '@angular/core'; +import { FirebaseApp, initializeBrowserOrServerApp, provideFirebaseApp } from '@angular/fire/app'; import { getAuth, provideAuth } from '@angular/fire/auth'; import { getFirestore, provideFirestore } from '@angular/fire/firestore'; @@ -211,21 +210,7 @@ const firebaseConfig = { /* ...your Firebase configuration... */ }; export const appConfig: ApplicationConfig = { providers: [ - provideFirebaseApp(() => { - if (isPlatformBrowser(inject(PLATFORM_ID))) { - return initializeApp(firebaseConfig); - } - const requestContext = inject(REQUEST_CONTEXT, { optional: true }) as - | { authIdToken?: string } - | null; - if (!requestContext?.authIdToken) { - return initializeApp(firebaseConfig); - } - return initializeServerApp(firebaseConfig, { - authIdToken: requestContext.authIdToken, - releaseOnDeref: requestContext, - }); - }), + provideFirebaseApp(() => initializeBrowserOrServerApp(firebaseConfig)), provideAuth(() => getAuth(inject(FirebaseApp))), provideFirestore(() => getFirestore(inject(FirebaseApp))), // ... @@ -233,42 +218,162 @@ export const appConfig: ApplicationConfig = { }; ``` -#### Five details make this work +`initializeBrowserOrServerApp` returns the right kind of app for where the code is running: + +- In the browser, the ordinary Firebase app, as `initializeApp(firebaseConfig)` would. +- On the server, when the request context carries an `authIdToken`, a [`FirebaseServerApp`](https://firebase.google.com/docs/web/ssr-apps) signed in as that visitor. The same goes for an `appCheckToken`, see [Relaying the App Check token](#relaying-the-app-check-token). +- On the server with neither token, which is what prerendering and a signed-out visitor look like, the ordinary Firebase app, so the page renders signed out. +- On the server with a token Firebase cannot parse, the ordinary Firebase app after a warning in the server console, so the page renders signed out instead of failing the request. + +#### Three details make this work + +- **Keep exactly one `provideFirebaseApp`.** AngularFire hands you the app you provided only when a single one is registered, and falls back to the default app otherwise. With a second registration anywhere in your configuration, a signed-in render uses the default app instead of the server app, and the page renders signed out without an error. If no registration creates the default app, as with two `initializeBrowserOrServerApp` registrations, signed-in renders fail instead until a signed-out request has created it. +- **Pass `inject(FirebaseApp)` to every provider, not just `provideAuth`.** `ng add @angular/fire` writes them without an argument, which resolves the default app. On a signed-in request the app is a server app instead, so a provider that asks for the default app fails outright on a freshly started server. +- **Never call `deleteApp` on the injected app.** `initializeBrowserOrServerApp` releases the server app itself. A second release from your code can delete an app another render is still using. + +#### When the server app is released + +By default the server app is released once the garbage collector has reclaimed the finished request, which is also what the manual setup below does. Until then, a repeat request from the same visitor, such as a reload or a link opened in a new tab, reuses the app, and that reuse is what keeps such a request as fast as a signed-out one. A fresh server app costs a new Firestore connection and an account lookup, about 300 to 400 ms before the HTML is sent. + +To release at a fixed time instead, pass `releaseAfterRender`: `0` releases the app as soon as the page has been rendered, which bounds memory to the requests in flight and pays that cost on every repeat request, and a positive number keeps the app for that many milliseconds after the page has been rendered. + +```ts +provideFirebaseApp(() => initializeBrowserOrServerApp(firebaseConfig, { releaseAfterRender: 60_000 })), +``` -- **Keep exactly one `provideFirebaseApp`.** AngularFire hands you the app you provided only when a single one is registered, and falls back to the default app otherwise. A second registration anywhere in your configuration would make the server app be silently ignored. -- **Pass `inject(FirebaseApp)` to every provider, not just `provideAuth`.** `ng add @angular/fire` writes them without an argument, which resolves the default app. On a signed-in request the factory above builds a server app instead, so a provider that asks for the default app fails outright on a freshly started server. -- **Keep the signed-out fallback.** There is no request context when Angular prerenders a page, and no token when the visitor is signed out, so the fallback builds an ordinary Firebase app and the page renders signed out. -- **Pass `releaseOnDeref`.** It tells the SDK when it may release the server app. The SDK watches the object you give it and releases once that object is garbage collected, so pass one that lives exactly as long as the render, such as the request context itself. Leave it out and the SDK requires you to call `deleteApp` yourself for each server app you create. -- **The cast is needed** because Angular types `REQUEST_CONTEXT` as `unknown`. +A JavaScript runtime without `FinalizationRegistry` cannot release at garbage collection, so there the app is released as soon as the page has been rendered, whatever the setting. -AngularFire's [sample app](https://github.com/angular/angularfire/tree/main/sample) does this differently, giving the browser and the server their own `app.config.client.ts` and `app.config.server.ts` instead of deciding at runtime, inside a single `provideFirebaseApp` factory, which of `initializeApp` and `initializeServerApp` to call. That is also fine, and it keeps the server-only code out of the browser bundle, at the cost of an extra file to wire up. +With `releaseAfterRender` set, the Firebase app release is done in a `DestroyRef.onDestroy` callback, which Angular runs after every service's and component's `ngOnDestroy` when it destroys the request's injector. If an `ngOnDestroy` method or an `ApplicationRef.onDestroy` listener throws, Angular stops there, the release never runs, and the server app stays in memory, one per signed-in render. The default release does not run during that teardown and is not affected. -ID tokens are short-lived, and a returning visitor's browser can send one that expired while the tab was closed. The server cannot refresh it, because a user restored from an ID token has no refresh token, so Firebase logs an error and the page renders signed out. The browser then refreshes the token and the page updates. +Call `initializeBrowserOrServerApp` in `app.config.ts`, not in a route's `providers`. A route's `providers` create a child injector that Angular does not destroy when the request finishes, so a `releaseAfterRender` release registered there never runs. The default release is tied to the request's root injector and still happens. + +The [sample app on the `main` branch](https://github.com/angular/angularfire/tree/main/sample) is an example of this step: one `provideFirebaseApp(() => initializeBrowserOrServerApp(...))` in its shared `app.config.ts`, with `app.config.server.ts` adding only `provideServerRendering`. That sample is an Angular 22 app. The `initializeBrowserOrServerApp` call is the same on Angular 21. + +ID tokens are short-lived, and a returning visitor's browser can send one that expired while the tab was closed. The server cannot refresh it, because a user restored from an ID token has no refresh token, so Firebase logs an error and the page renders signed out. The browser then refreshes the token and the page updates. A token that cannot be parsed at all, such as a cookie another site set under the same name, also renders signed out, with one warning in the server console. + +If you would rather build the app yourself, or your AngularFire version has no `initializeBrowserOrServerApp`, see [Building the app yourself](#building-the-app-yourself) below. ### Using `REQUEST` instead of a cookie -Angular also exposes the request itself through the `REQUEST` token, so you can read the ID token from an `Authorization` header rather than a cookie. Firebase's [session management with service workers](https://firebase.google.com/docs/auth/web/service-worker-sessions) guide covers attaching that header. Steps 1, 3 and 4 stay the same apart from the server half of the factory, which becomes: +Angular also exposes the request itself through the `REQUEST` token, so you can read the ID token from an `Authorization` header rather than a cookie. Firebase's [session management with service workers](https://firebase.google.com/docs/auth/web/service-worker-sessions) guide covers attaching that header. Steps 1, 3 and 4 stay the same apart from the call in step 4, which passes the token explicitly: + +```ts +import { REQUEST, inject } from '@angular/core'; + +provideFirebaseApp(() => initializeBrowserOrServerApp(firebaseConfig, { + authIdToken: inject(REQUEST, { optional: true })?.headers.get('authorization')?.split('Bearer ')[1], +})), +``` + +`REQUEST` is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request), so headers are read with `headers.get(...)`. Angular sets it to `null` during builds, during static site generation, and during route extraction in development, and it is only supplied at all on `RenderMode.Server` routes. A missing header gives `undefined`, and `initializeBrowserOrServerApp` then looks in the request context and falls back to the ordinary app. + +### Relaying the App Check token + +If you [enforce App Check](https://firebase.google.com/docs/app-check/enable-enforcement) for a Firebase product, server renders need an App Check token too, or their requests are rejected. The server cannot mint one, so the browser relays its own, and `initializeBrowserOrServerApp` passes it to the server app as `appCheckToken`. + +Relay the ordinary token from `getToken`, not a limited-use one. Replay protection only applies where a backend consumes the token, such as a callable Cloud Function with `consumeAppCheckToken`, and product enforcement for Firestore, Realtime Database and Storage does not. + +Keep both tokens in the one `__session` cookie, since behind Firebase Hosting no other cookie reaches your server. In the cookie sync from step 2, write the cookie as JSON and rewrite it whenever either token changes: + +```ts +import { AppCheck } from '@angular/fire/app-check'; +// imported from firebase/app-check so a token that never arrives does not hold the app busy +import { getToken, onTokenChanged } from 'firebase/app-check'; + +const appCheck = inject(AppCheck, { optional: true }); +let authIdToken: string | undefined; +let appCheckToken: string | undefined; + +const writeSessionCookie = () => { + if (!authIdToken && !appCheckToken) { + cookies.remove('__session'); + return; + } + cookies.set('__session', JSON.stringify({ authIdToken, appCheckToken }), { secure: true, sameSite: 'lax' }); +}; + +idToken(auth) + .pipe(takeUntilDestroyed(destroyRef)) + .subscribe((token) => { + authIdToken = token ?? undefined; + writeSessionCookie(); + }); + +if (appCheck) { + destroyRef.onDestroy(onTokenChanged(appCheck, (result) => { + appCheckToken = result.token; + writeSessionCookie(); + })); + getToken(appCheck).then((result) => { + appCheckToken = result.token; + writeSessionCookie(); + }); +} +``` + +The `beforeAuthStateChanged` part of step 2 stays as it is, writing `authIdToken` and calling `writeSessionCookie()` instead of passing the token in. In `server.ts`, unpack the cookie and pass both keys: ```ts -import { PLATFORM_ID, REQUEST, inject } from '@angular/core'; +const readSessionCookie = (value: unknown): { authIdToken?: string; appCheckToken?: string } => { + if (typeof value !== 'string') { + return {}; + } + try { + return JSON.parse(value); + } catch { + return {}; + } +}; + +app.use((req, res, next) => { + res.setHeader('Cache-Control', 'private, no-store'); + angularApp + .handle(req, readSessionCookie(req.cookies?.__session)) + .then((response) => + response ? writeResponseToNodeResponse(response, res) : next(), + ) + .catch(next); +}); +``` + +Three things to know before relaying it: + +- **Every visitor's first server render builds a server app.** An App Check token is per device, so even signed-out visitors get a server app carrying it, and that first render pays the 300 to 400 ms described above. Relay the token only if you enforce App Check. +- **A stale cookie fails the first request after the token's lifetime.** The browser rewrites the cookie only after the page's JavaScript has run and Firebase has refreshed the token. A visitor who returns after about an hour sends the old one, so that first server render's Firebase requests are rejected under enforcement, and the page shows whatever your app shows for a failed read until it hydrates and reads again. For the ID token the same stale first request only means a signed-out render. If that first render must succeed, Firebase's [service-worker relay](https://firebase.google.com/docs/web/ssr-apps#use-app-check) refreshes the token before the request leaves the browser, at the cost of a service worker your app registers itself. +- **A relayed token wins over `APP_CHECK_ON_SERVER` for Firestore.** When the server app carries an `appCheckToken`, Firestore sends it whatever App Check instance the server holds. + +### Building the app yourself + +If you would rather build the app yourself, or your AngularFire version does not export `initializeBrowserOrServerApp`, choose the app in step 4 with your own callback. The `try` around `initializeServerApp` is what keeps a token Firebase cannot parse from failing the request with an HTTP 500, and `releaseOnDeref` is what releases the server app, the way `initializeBrowserOrServerApp` does by default: + +```ts +import { PLATFORM_ID, REQUEST_CONTEXT, inject } from '@angular/core'; +import { isPlatformBrowser } from '@angular/common'; +import { initializeApp, initializeServerApp } from '@angular/fire/app'; + +const hasAuthIdToken = (value: unknown): value is { authIdToken: string } => + typeof value === 'object' && value !== null && typeof Reflect.get(value, 'authIdToken') === 'string'; provideFirebaseApp(() => { if (isPlatformBrowser(inject(PLATFORM_ID))) { return initializeApp(firebaseConfig); } - const request = inject(REQUEST, { optional: true }); - const authIdToken = request?.headers.get('authorization')?.split('Bearer ')[1]; - if (!authIdToken) { + const requestContext = inject(REQUEST_CONTEXT, { optional: true }); + if (!hasAuthIdToken(requestContext) || !requestContext.authIdToken) { + return initializeApp(firebaseConfig); + } + try { + return initializeServerApp(firebaseConfig, { + authIdToken: requestContext.authIdToken, + releaseOnDeref: requestContext, + }); + } catch { return initializeApp(firebaseConfig); } - return initializeServerApp(firebaseConfig, { - authIdToken, - releaseOnDeref: request, - }); }), ``` -`REQUEST` is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request), so headers are read with `headers.get(...)`. Angular sets it to `null` during builds, during static site generation, and during route extraction in development, and it is only supplied at all on `RenderMode.Server` routes, so keep the signed-out fallback for those passes. +Keep the signed-out fallback, since there is no request context when Angular prerenders a page and no token when the visitor is signed out, and keep the first two of the three details above. An app that already has this callback can switch to `initializeBrowserOrServerApp` in one deploy. The callback keeps working on later versions too. ## Convenience observables diff --git a/docs/compat.md b/docs/compat.md index bd8721b25..3364538b0 100644 --- a/docs/compat.md +++ b/docs/compat.md @@ -9,6 +9,81 @@ AngularFire has a new tree-shakable API, you're looking at the documentation for [See the v7 upgrade guide for more information on this change.](version-7-upgrade.md). +### Support status + +The compatibility API (`@angular/fire/compat/*`) is still supported. It gets bug fixes but no new features, which go into the modular API only. There are no plans to remove it, so you can keep upgrading AngularFire without migrating. + +Some of its tests are turned off right now: the ones for `AngularFirestoreCollection`, `AngularFirestoreCollectionGroup` and `AngularFirestoreDocument`, and one Cloud Storage upload test. Until [#3822](https://github.com/angular/angularfire/issues/3822) turns them back on, a bug in those APIs may not be caught before a release, so please report any you find. + +### Setup + +Install AngularFire and Firebase with `ng add @angular/fire`, as in [the quickstart](install-and-setup.md#2-install-angularfire-and-firebase) (its "Before you begin" notes apply here too), or with `npm install @angular/fire firebase`. + +At the `ng add` feature prompt, select the products you use: `ng add` then writes the modular providers (`provideFirebaseApp(...)` and one per selected feature) into your app configuration with your Firebase configuration inlined, and with nothing selected it installs the packages and sets up nothing. + +The compat API does not use the modular providers. It needs `AngularFireModule.initializeApp(...)` with your Firebase configuration, plus the compat module of each Firebase product you use. + +The modular providers can stay if `AngularFireModule.initializeApp(...)` gets the same configuration object, both APIs then share one Firebase app. With two different configurations, whichever API starts second fails with `app/duplicate-app`. + +In a standalone application, add them to `app.config.ts`: + +```ts +import { ApplicationConfig, importProvidersFrom } from '@angular/core'; +import { AngularFireModule } from '@angular/fire/compat'; +import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; + +export const appConfig: ApplicationConfig = { + providers: [ + importProvidersFrom( + AngularFireModule.initializeApp({ /* your Firebase configuration */ }), + AngularFireDatabaseModule, + ), + ], +}; +``` + +In an NgModule application, import them in `app-module.ts`: + +```ts +import { NgModule } from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; +import { AngularFireModule } from '@angular/fire/compat'; +import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; +import { App } from './app'; + +@NgModule({ + declarations: [App], + imports: [ + BrowserModule, + AngularFireModule.initializeApp({ /* your Firebase configuration */ }), + AngularFireDatabaseModule, + ], + bootstrap: [App], +}) +export class AppModule {} +``` + +Without `AngularFireModule.initializeApp(...)`, injecting a compat service fails with `NG0201`, which a development build reports as: + +``` +NG0201: No provider found for `InjectionToken angularfire2.app.options`. +``` + +The compat module for each product: + +| Product | Module | Import from | +|---|---|---| +| Analytics | `AngularFireAnalyticsModule` | `@angular/fire/compat/analytics` | +| Authentication | `AngularFireAuthModule` | `@angular/fire/compat/auth` | +| Authentication route guards | `AngularFireAuthGuardModule` | `@angular/fire/compat/auth-guard` | +| Cloud Firestore | `AngularFirestoreModule` | `@angular/fire/compat/firestore` | +| Cloud Functions | `AngularFireFunctionsModule` | `@angular/fire/compat/functions` | +| Cloud Messaging | `AngularFireMessagingModule` | `@angular/fire/compat/messaging` | +| Cloud Storage | `AngularFireStorageModule` | `@angular/fire/compat/storage` | +| Performance Monitoring | `AngularFirePerformanceModule` | `@angular/fire/compat/performance` | +| Realtime Database | `AngularFireDatabaseModule` | `@angular/fire/compat/database` | +| Remote Config | `AngularFireRemoteConfigModule` | `@angular/fire/compat/remote-config` | + ### Monitor usage of your application in production > `AngularFireAnalytics` provides a convenient method of interacting with Google Analytics in your Angular application. The provided `ScreenTrackingService` and `UserTrackingService` automatically log events when you're using the Angular Router or Firebase Authentication respectively. [Learn more about Google Analytics](https://firebase.google.com/docs/analytics). diff --git a/docs/compat/analytics/getting-started.md b/docs/compat/analytics/getting-started.md index 3c5af8aaf..f6a64ba6e 100644 --- a/docs/compat/analytics/getting-started.md +++ b/docs/compat/analytics/getting-started.md @@ -1,6 +1,6 @@ # Getting started with Google Analytics -`AngularFireAnalytics` dynamically imports the `firebase/analytics` library and provides a promisified version of the [Firebase Analytics SDK (`firebase.analytics.Analytics`)](https://firebase.google.com/docs/reference/js/firebase.analytics.Analytics.html). +`AngularFireAnalytics` dynamically imports the `firebase/analytics` library and provides a promisified version of the [Firebase Analytics SDK (`firebase.analytics.Analytics`)](https://firebase.google.com/docs/reference/js/v8/firebase.analytics.Analytics.html). > **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). @@ -40,6 +40,8 @@ import { AngularFireAnalyticsModule } from '@angular/fire/compat/analytics'; export class AppModule { } ``` +For a standalone application, and the compat module of every product, see the [compat guide's Setup section](../../compat.md#setup). + `AngularFireAnalyticsModule` will dynamically import and configure `firebase/analytics`. A `page_view` event will automatically be logged (see `CONFIG` below if you wish to disable this behavior.) In your component you can then dependency inject `AngularFireAnalytics` and make calls against the SDK: @@ -54,7 +56,7 @@ constructor(analytics: AngularFireAnalytics) { ## Tracking Screen Views -You can log [`screen_view` events](https://firebase.google.com/docs/reference/js/firebase.analytics.Analytics.html#parameters_10) yourself of course, but AngularFire provides the `ScreenTrackingService` which automatically integrates with the Angular Router to provide Firebase with screen view tracking. You simply can integrate like so: +You can log [`screen_view` events](https://firebase.google.com/docs/reference/js/v8/firebase.analytics.Analytics.html#parameters_10) yourself of course, but AngularFire provides the `ScreenTrackingService` which automatically integrates with the Angular Router to provide Firebase with screen view tracking. You simply can integrate like so: ```ts import { AngularFireAnalyticsModule, ScreenTrackingService } from '@angular/fire/compat/analytics'; @@ -75,7 +77,7 @@ export class AppModule { } ## Tracking User Identifiers -To enrich your Analytics data you can track the currently signed in user by setting [`setuserid`](https://firebase.google.com/docs/reference/js/firebase.analytics.Analytics.html#setuserid) and [`setUserProperties`](https://firebase.google.com/docs/reference/js/firebase.analytics.Analytics.html#set-user-properties). AngularFire provides a `UserTrackingService` which will dynamically import `firebase/auth`, monitor for changes in the logged in user, and call `setuserid` for you automatically. +To enrich your Analytics data you can track the currently signed in user by setting [`setuserid`](https://firebase.google.com/docs/reference/js/v8/firebase.analytics.Analytics.html#setuserid) and [`setUserProperties`](https://firebase.google.com/docs/reference/js/v8/firebase.analytics.Analytics.html#setuserproperties). AngularFire provides a `UserTrackingService` which will dynamically import `firebase/auth`, monitor for changes in the logged in user, and call `setuserid` for you automatically. ```ts diff --git a/docs/compat/auth/getting-started.md b/docs/compat/auth/getting-started.md index 48aed34b6..368306658 100644 --- a/docs/compat/auth/getting-started.md +++ b/docs/compat/auth/getting-started.md @@ -8,6 +8,8 @@ the Firebase docs for more information on what methods are available.](https://f > **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). +Setup for the compat API, `AngularFireModule.initializeApp(...)` plus `AngularFireAuthModule`, is in the [compat guide's Setup section](../../compat.md#setup). + **Example app:** ```ts diff --git a/docs/compat/firestore/collections.md b/docs/compat/firestore/collections.md index 709a969c5..95f50e95e 100644 --- a/docs/compat/firestore/collections.md +++ b/docs/compat/firestore/collections.md @@ -5,6 +5,8 @@ Each *document* contains a set of key-value pairs. Cloud Firestore is optimized > **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). +Setup for the compat API, `AngularFireModule.initializeApp(...)` plus `AngularFirestoreModule`, is in the [compat guide's Setup section](../../compat.md#setup). + ## Using `AngularFirestoreCollection` The `AngularFirestoreCollection` service is a wrapper around the native Firestore SDK's [`CollectionReference`](https://firebase.google.com/docs/reference/js/v8/firebase.firestore.CollectionReference) and [`Query`](https://firebase.google.com/docs/reference/js/v8/firebase.firestore.Query) types. It is a generic service that provides you with a strongly typed set of methods for manipulating and streaming data. This service is designed for use as an `@Injectable()`. diff --git a/docs/compat/firestore/documents.md b/docs/compat/firestore/documents.md index c59624685..009198d7d 100644 --- a/docs/compat/firestore/documents.md +++ b/docs/compat/firestore/documents.md @@ -5,9 +5,11 @@ Each *document* contains a set of key-value pairs. Cloud Firestore is optimized > **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). +Setup for the compat API, `AngularFireModule.initializeApp(...)` plus `AngularFirestoreModule`, is in the [compat guide's Setup section](../../compat.md#setup). + ## Using `AngularFirestoreDocument` -The `AngularFirestoreDocument` service is a wrapper around the native Firestore SDK's [`DocumentReference` type](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference). It is a generic service that provides you with a strongly typed set of methods for manipulating and streaming data. This service is designed for use as an `@Injectable()`. +The `AngularFirestoreDocument` service is a wrapper around the native Firestore SDK's [`DocumentReference` type](https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference). It is a generic service that provides you with a strongly typed set of methods for manipulating and streaming data. This service is designed for use as an `@Injectable()`. ```ts import { Component } from '@angular/core'; diff --git a/docs/compat/firestore/offline-data.md b/docs/compat/firestore/offline-data.md index 3e16b845c..5698d584c 100644 --- a/docs/compat/firestore/offline-data.md +++ b/docs/compat/firestore/offline-data.md @@ -32,6 +32,8 @@ export class AppModule {} ``` +For a standalone application, and the compat module of every product, see the [compat guide's Setup section](../../compat.md#setup). + While offline your listeners will receive listen events when the locally cached data changes. You can use to Documents and Collections normally. To check whether you're receiving data from the server or the cache, use the `fromCache` property on the `SnapshotMetadata` in your snapshot event. If `fromCache` is true, the data came from the cache and might be stale or incomplete. If `fromCache` is false, the data is complete and current with the latest updates on the server. diff --git a/docs/compat/functions/functions.md b/docs/compat/functions/functions.md index 708788ca7..b43c9f70d 100644 --- a/docs/compat/functions/functions.md +++ b/docs/compat/functions/functions.md @@ -28,6 +28,8 @@ import { environment } from '../environments/environment'; export class AppModule {} ``` +For a standalone application, and the compat module of every product, see the [compat guide's Setup section](../../compat.md#setup). + ### Injecting the AngularFireFunctions service Once the `AngularFireFunctionsModule` is registered you can inject the `AngularFireFunctions` service. diff --git a/docs/compat/messaging/messaging.md b/docs/compat/messaging/messaging.md index 593e59003..ec8e88377 100644 --- a/docs/compat/messaging/messaging.md +++ b/docs/compat/messaging/messaging.md @@ -38,6 +38,8 @@ import { environment } from '../environments/environment'; export class AppModule {} ``` +For a standalone application, and the compat module of every product, see the [compat guide's Setup section](../../compat.md#setup). + ### Setting up the Firebase Messaging Service Worker There are two parts to Firebase Messaging, a Service Worker and the DOM API. AngularFireMessaging allows you to request permission, get tokens, delete tokens, and subscribe to messages on the DOM side. To register to receive notifications you need to set up the Service Worker. [The official Firebase documentation for setting up the details exactly how to do that](https://firebase.google.com/docs/cloud-messaging/js/client). diff --git a/docs/compat/performance/getting-started.md b/docs/compat/performance/getting-started.md index c435693bf..0d6bc422d 100644 --- a/docs/compat/performance/getting-started.md +++ b/docs/compat/performance/getting-started.md @@ -27,6 +27,8 @@ import { environment } from '../environments/environment'; export class AppModule {} ``` +For a standalone application, and the compat module of every product, see the [compat guide's Setup section](../../compat.md#setup). + The page load trace breaks down into the following default metrics: * [first paint traces](https://firebase.google.com/docs/perf-mon/automatic-web#first-paint) — measure the time between when the user navigates to a page and when any visual change happens diff --git a/docs/compat/remote-config/getting-started.md b/docs/compat/remote-config/getting-started.md index ab4bfa049..04babd51d 100644 --- a/docs/compat/remote-config/getting-started.md +++ b/docs/compat/remote-config/getting-started.md @@ -1,6 +1,6 @@

Getting started with Remote Config β

-`AngularFireRemoteConfig` dynamically imports the `firebase/remote-config` library on demand, provides convenience observables, pipes, and a promisified version of the [Firebase Remote Config SDK (`firebase.remoteConfig.RemoteConfig`)](https://firebase.google.com/docs/reference/js/firebase.remoteconfig.RemoteConfig). +`AngularFireRemoteConfig` dynamically imports the `firebase/remote-config` library on demand, provides convenience observables, pipes, and a promisified version of the [Firebase Remote Config SDK (`firebase.remoteConfig.RemoteConfig`)](https://firebase.google.com/docs/reference/js/v8/firebase.remoteconfig.RemoteConfig). > **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). @@ -59,7 +59,7 @@ DEFAULTS = InjectionToken; ### Configure Remote Config with `SETTINGS` -Using the `SETTINGS` DI Token (*default: {}*) will allow you to [configure Firebase Remote Config](https://firebase.google.com/docs/reference/js/firebase.remoteconfig.Settings.html). +Using the `SETTINGS` DI Token (*default: {}*) will allow you to [configure Firebase Remote Config](https://firebase.google.com/docs/reference/js/v8/firebase.remoteconfig.Settings.html). ### Configure default values with `DEFAULTS` @@ -132,3 +132,5 @@ constructor(remoteConfig: AngularFireRemoteConfig) { remoteConfig.lastFetchStatus.then(status => ...); } ``` + +For a standalone application, and the compat module of every product, see the [compat guide's Setup section](../../compat.md#setup). diff --git a/docs/compat/rtdb/lists.md b/docs/compat/rtdb/lists.md index 084c54eeb..fcc0297cb 100644 --- a/docs/compat/rtdb/lists.md +++ b/docs/compat/rtdb/lists.md @@ -10,7 +10,7 @@ The guide below demonstrates how to retrieve, save, and remove data as lists. ## Injecting the `AngularFireDatabase` service -**Make sure you have bootstrapped your application for AngularFire. See the Installation guide for bootstrap setup.** +**Make sure you have set up AngularFire for the compat API, see [Setup](../../compat.md#setup).** AngularFireDatabase is a service which can be injected through the constructor of your Angular component or `@Injectable()` service. In the previous step, we modified the `/src/app/app.component.ts` to retrieve data as an object. In this step, let's start with a clean slate. diff --git a/docs/compat/rtdb/objects.md b/docs/compat/rtdb/objects.md index 76c9725ee..b68ca21cb 100644 --- a/docs/compat/rtdb/objects.md +++ b/docs/compat/rtdb/objects.md @@ -10,11 +10,11 @@ The guide below demonstrates how to retrieve, save, and remove data as objects. ## Injecting the `AngularFireDatabase` service -**Make sure you have bootstrapped your application for AngularFire. See the Installation guide for bootstrap setup.** +**Make sure you have set up AngularFire for the compat API, see [Setup](../../compat.md#setup).** `AngularFireDatabase` is a service which can be injected through the constructor of your Angular component or `@Injectable()` service. -If you've followed the earlier step "Installation and Setup" your `/src/app/app.component.ts` should look like below. +With the [Setup](../../compat.md#setup) done, inject `AngularFireDatabase` into a component, for example: ```ts import { Component } from '@angular/core'; diff --git a/docs/compat/rtdb/querying-lists.md b/docs/compat/rtdb/querying-lists.md index 1279d800c..db646c7bb 100644 --- a/docs/compat/rtdb/querying-lists.md +++ b/docs/compat/rtdb/querying-lists.md @@ -4,7 +4,7 @@ ## Creating a query with primitive/scalar values -Queries are created by building on the [`firebase.database.Reference`](https://firebase.google.com/docs/reference/js/firebase.database.Reference). +Queries are created by building on the [`firebase.database.Reference`](https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference). ```ts db.list('/items', ref => ref.orderByChild('size').equalTo('large')) @@ -26,7 +26,7 @@ db.list('/items', ref => ref.orderByChild('size').equalTo('large')) 1 [This is the old way of doing things and is no longer recommended for use](https://youtu.be/3WTQZV5-roY?t=3m). Anything you can achieve with `orderByPriority` you should be doing with `orderByChild`. -2 The Firebase SDK supports an optional `key` parameter for [`startAt`](https://firebase.google.com/docs/reference/js/firebase.database.Reference#startAt), [`endAt`](https://firebase.google.com/docs/reference/js/firebase.database.Reference#endAt), and [`equalTo`](https://firebase.google.com/docs/reference/js/firebase.database.Reference#equalTo) when ordering by child, value, or priority. You can specify the `key` parameter using an object literal that contains the `value` and the `key`. For example: `startAt: { value: 'some-value', key: 'some-key' }`. +2 The Firebase SDK supports an optional `key` parameter for [`startAt`](https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference#startat), [`endAt`](https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference#endat), and [`equalTo`](https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference#equalto) when ordering by child, value, or priority. You can specify the `key` parameter using an object literal that contains the `value` and the `key`. For example: `startAt: { value: 'some-value', key: 'some-key' }`. To learn more about how sorting and ordering data works in Firebase, check out the Firebase documentation on [working with lists of data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data). diff --git a/docs/compat/storage/storage.md b/docs/compat/storage/storage.md index 867805041..22b0e8ba4 100644 --- a/docs/compat/storage/storage.md +++ b/docs/compat/storage/storage.md @@ -28,6 +28,8 @@ import { environment } from '../environments/environment'; export class AppModule {} ``` +For a standalone application, and the compat module of every product, see the [compat guide's Setup section](../../compat.md#setup). + The `BUCKET` injection token can be used to customise the storage bucket. ```ts diff --git a/docs/database.md b/docs/database.md index 1eac2244b..dcc1f39ea 100644 --- a/docs/database.md +++ b/docs/database.md @@ -100,6 +100,8 @@ The `listVal()` function creates an observable that emits an object mapped to it The `stateChanges()` function creates an observable that emits each time a change occurs at the reference or query passed. This is useful for tracking the changes in your list. The optional `events` parameter will filter which child events populate the array. +It emits only on child events, which an empty list never produces, so it does not hold the application unstable and a server render does not wait for it. Use `list()` when the render should wait for a list's initial contents. + | | | |-----------------|------------------------------------------------------| | **function** | `stateChanges(ref, options?)` | @@ -110,6 +112,8 @@ The `stateChanges()` function creates an observable that emits each time a chang The `auditTrail()` function creates an observable that emits the entire state trail. This is useful for debugging or replaying the state of a list in your app. The optional `events` parameter will filter which child events populate the array. +Like `stateChanges()`, it waits for child events, so it does not hold the application unstable and a server render does not wait for it. + | | | |-----------------|------------------------------------------------------| | **function** | `auditTrail(ref, options?)` | @@ -120,6 +124,8 @@ The `auditTrail()` function creates an observable that emits the entire state tr The `fromRef()` function creates an observable that emits reference changes. +With `ListenEvent.value` it holds the application unstable until the first value is emitted, so a server render waits for the data. With a child event it does not, because it may never emit. + | | | |-----------------|------------------------------------------| | **function** | `fromRef(ref, event)` | diff --git a/docs/firestore.md b/docs/firestore.md index 51a682329..551e56337 100644 --- a/docs/firestore.md +++ b/docs/firestore.md @@ -105,10 +105,27 @@ Let's explore reading data in Angular using the `collection` and `collectionData In `user-profile.component.ts`: ```typescript -import { Firestore, collection, collectionData} from '@angular/fire/firestore'; +import { Firestore, FirestoreDataConverter, collection, collectionData } from '@angular/fire/firestore'; import { Component, inject } from '@angular/core'; import { Observable } from 'rxjs'; +export interface UserProfile { + username: string; +} + +/* A converter translates between stored documents and your own type. + * fromFirestore runs on every document read, so it is where a missing + * or wrong field gets its default. */ +export const userProfileConverter: FirestoreDataConverter = { + toFirestore: profile => profile, + fromFirestore: (snapshot, options) => { + const data = snapshot.data(options); + return { + username: typeof data['username'] === 'string' ? data['username'] : '', + }; + }, +}; + @Component ({ selector: 'app-user-profile', standalone: true, @@ -119,17 +136,15 @@ export class UserProfileComponent { users$: Observable; constructor() { - // get a reference to the user-profile collection - const userProfileCollection = collection(this.firestore, 'users'); + // get a reference to the users collection, typed through the converter + const userProfileCollection = collection(this.firestore, 'users').withConverter(userProfileConverter); // get documents (data) from the collection using collectionData - this.users$ = collectionData(userProfileCollection) as Observable; + this.users$ = collectionData(userProfileCollection); // Observable } } -export interface UserProfile { - username: string; -} ``` + `collectionData` returns an `observable` that can we can use to display the data in the template. In `user-profile.component.html`: ```html @@ -145,6 +160,17 @@ export interface UserProfile { The `async` pipe handles unsubscribing from observables. +#### Typed reads + +`collection()` and `doc()` return references typed as `DocumentData`, and `collectionData()` and `docData()` return whatever type the reference carries (`docData()` adds `undefined` for a document that does not exist). Two tempting shortcuts do not give you a typed read: + +* `collectionData(collection(this.firestore, 'users'))` does not compile (`TS2345`), because the reference says `DocumentData` and the type argument says `UserProfile`. +* `collectionData(...) as Observable` compiles, but it only tells the compiler what you hope is stored. Nothing checks the documents. + +`withConverter()` is the Firebase SDK's way to type a reference. Attach a `FirestoreDataConverter` and every read through that reference returns `T`, with no type argument and no cast. Because `fromFirestore` runs on every document, it is also where you decide what happens to a document that does not match your type. The example above substitutes a default, so one malformed document does not stop the list from rendering. Throwing inside `fromFirestore` instead would error the `collectionData` observable at the first bad document, and the subscription would end. + +The `idField` option, `collectionData(ref, { idField: 'id' })`, copies each document's id onto the returned object. It does not validate any other field. With a converter you can do the same inside `fromFirestore` with `snapshot.id`. + ### Writing data To write to Cloud Firestore use the `addDoc` function. It will create a new document at the path specified by the collection. In `user-profile.component.ts`, we'll update the code to add a new document on a `