Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion docs/app-hosting.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,21 @@

This guide covers one thing that trips up almost every new SSR deployment: **the server can silently stop server-rendering and fall back to client-side rendering (CSR), with no error anywhere obvious.** It explains how to detect that in 30 seconds and how to fix it.

## Contents

- [How to deploy](#how-to-deploy)
- [The symptom: SSR silently downgrades to CSR](#the-symptom-ssr-silently-downgrades-to-csr)
- [The 30-second check to run after every deploy](#the-30-second-check-to-run-after-every-deploy)
- [Why it happens](#why-it-happens)
- [The Fix](#the-fix)
- [Why both steps](#why-both-steps)
- [Related Angular documentation](#related-angular-documentation)

## How to deploy

If you have not deployed yet, follow Firebase's own guides: [Get started with App Hosting](https://firebase.google.com/docs/app-hosting/get-started) to connect a GitHub repository (App Hosting builds and deploys on every push), or [Alternative ways to deploy](https://firebase.google.com/docs/app-hosting/alt-deploy) to deploy with `firebase deploy` from your own machine. Both build your app the same way in Google Cloud Build. The rest of this guide covers an Angular-specific issue you can hit once your app is deployed either way.
If you have not deployed yet, `ng add @angular/fire` can set up `ng deploy` for App Hosting. The [deploy guide](deploy/getting-started.md) explains how. `ng deploy` uploads your workspace the way `firebase deploy` does.

You can also follow Firebase's own guides: [Get started with App Hosting](https://firebase.google.com/docs/app-hosting/get-started) to connect a GitHub repository (App Hosting builds and deploys on every push), or [Alternative ways to deploy](https://firebase.google.com/docs/app-hosting/alt-deploy) to deploy with `firebase deploy` from your own machine. All of these build your app the same way in Google Cloud Build. The rest of this guide covers an Angular-specific issue you can hit once your app is deployed any of these ways.

## The symptom: SSR silently downgrades to CSR

Expand Down
312 changes: 178 additions & 134 deletions docs/deploy/getting-started.md

Large diffs are not rendered by default.

26 changes: 16 additions & 10 deletions docs/install-and-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,32 @@
- Setup uses the Firebase CLI (`firebase-tools`). Install it with `npm install -g firebase-tools`, then run `firebase login`. If `ng add` can't find a copy, it installs the newest version for you.
- A copy older than 14 stops setup with `firebase-tools version 14.0.0+ is required, please upgrade and run again`, and `ng add` does not upgrade a copy you already have.
- If `ng add` stops before finishing, run it again. A stopped run leaves only an empty `firebase.json`, which the next run reuses.
- **npm 11.6 or later**, if you use npm. Older versions, including the npm 10 that ships with Node.js 20 and 22, cannot install a new Angular 21 project ([npm/cli#9787](https://github.com/npm/cli/issues/9787), `Cannot read properties of null (reading 'edgesOut')`). Update with `npm install -g npm@11`.
- If it already failed, delete the project folder it left behind before running the command again.
- **Harmless CLI noise.** The Firebase CLI may print a `punycode` deprecation warning or ask about enabling extra features (for example Gemini) during setup. These come from the CLI, not from AngularFire, and are safe to ignore.

### 1. Create a new project

```bash
# Using yarn create
yarn create @angular@21 <project-name>
yarn create @angular@22 <project-name>
cd <project-name>
```
or

```bash
# Using npm create
npm create @angular@21 <project-name>
npm create @angular@22 <project-name>
cd <project-name>
```

optionally installing the tooling directly:
```bash
# Installing the tooling directly
npm install -g @angular/cli@21
npm install -g @angular/cli@22
ng new <project-name>
cd <project-name>
```

These commands set up an Angular 21 project, the version AngularFire 21 supports.
These commands set up an Angular 22 project, the version AngularFire 22 supports.

### 2. Install AngularFire and Firebase

Expand All @@ -44,7 +42,8 @@ ng add @angular/fire
This installs AngularFire and configures your project. `ng add` will:

1. Prompt you to select the features to enable and the Firebase project to use, signing you in to Firebase if needed.
2. Add `provideFirebaseApp(...)`, along with a provider for each feature you select, to your app configuration (for example `app.config.ts`), with your Firebase configuration inlined. No environment files are created.
2. Ask how you want to deploy your app, and set up `ng deploy` for your answer. Step 6 explains the choices.
3. Add `provideFirebaseApp(...)`, along with a provider for each feature you select, to your app configuration (for example `app.config.ts`), with your Firebase configuration inlined. No environment files are created.

### 3. Inject `Firestore`

Expand Down Expand Up @@ -136,8 +135,15 @@ Once you've created a `items` collection and are inserting documents, you should

### 6. Deploy your app

How you deploy depends on whether your app uses server-side rendering (SSR), which the Angular CLI asks about when you create the project.
In step 2, `ng add` asked how you want to deploy your app. If you chose Firebase App Hosting or Firebase Hosting, deploy with:

**Client-side rendered apps** (the default) build to static files, which you deploy to Firebase Hosting. Follow Firebase's [Hosting quickstart](https://firebase.google.com/docs/hosting/quickstart) to build and deploy your app.
```bash
ng deploy
```

- **Firebase App Hosting** runs a Node server, so it fits apps that use server-side rendering (SSR). `ng deploy` uploads your source, and App Hosting builds it in Google Cloud. It needs the Blaze pricing plan and Firebase CLI 15.9.0 or later.
- **Firebase Hosting** serves static files, so it fits client-side rendered and prerendered apps. `ng deploy` builds your app and uploads the build.

If you chose not to set up deployment, run `ng add @angular/fire` again. Press Enter at the features prompt without selecting anything, then pick a deploy option.

**Server-side rendered apps** run a Node server, so deploy them to [Firebase App Hosting](app-hosting.md), Firebase's recommended path for SSR. That guide also covers a common case where an SSR app silently falls back to client-side rendering after deploying.
The [deploy guide](deploy/getting-started.md) explains what `ng add` writes and what `ng deploy` does with it. For App Hosting, [Deploying SSR to App Hosting](app-hosting.md) also covers a common case where an SSR app silently falls back to client-side rendering after deploying.
13 changes: 12 additions & 1 deletion docs/messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ export class AppComponent {
}
```

`Messaging` is `null` during server rendering and in a browser with no service worker support, such as an iOS in-app browser or a page served over plain HTTP to another device, so check it before use.

# Create a Firebase Messaging Service Worker

There are two parts to Firebase Messaging, a Service Worker and the DOM API. Angular Fire Messaging allows you to request permission, register this app instance, observe when it is registered or unregistered, 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).
Expand Down Expand Up @@ -96,10 +98,15 @@ export class FcmService {
/* `onMessage` converted to an observable. Returns the unsubscribe function returned by
* `onMessage` to stop the listener when the last subscriber unsubscribes. */
message$ = new Observable<MessagePayload>(
subscriber => onMessage(this.msg, (msg) => subscriber.next(msg))
subscriber => this.msg ? onMessage(this.msg, (msg) => subscriber.next(msg)) : undefined
).pipe(tap((msg) => console.log("My Firebase Cloud Message", msg)));

constructor(private msg: Messaging) {
// `Messaging` is null during server rendering and where the browser has no service workers.
if (!this.msg) {
return;
}

// Set listeners before calling `register` to avoid throwing.
this.listenForRegistrationChanges();
this.registerForMessages();
Expand Down Expand Up @@ -144,6 +151,10 @@ export class FcmService {

// Called from your app, for example when a user turns notifications off.
async unregister() {
if (!this.msg) {
return;
}

// This calls the imported unregister, not this method. Class methods are not in lexical scope.
await unregister(this.msg);
}
Expand Down
2 changes: 2 additions & 0 deletions docs/remote-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export class RemoteConfigComponent {
}
```

`RemoteConfig` is `null` during server rendering, so check it before use.

## Firebase API

AngularFire wraps the Firebase JS SDK to ensure proper functionality in Angular, while providing the same API.
Expand Down
34 changes: 29 additions & 5 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,13 @@ With isolation on, every spec file loads its imports again, so the run takes lon

#### Mock the package, not your own files

Angular's Vitest setup rejects `vi.mock('./user-badge')` with the error: `The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system`. Replace your own services through `TestBed` providers.
Angular's Vitest setup rejects `vi.mock('./user-badge')` with this error:

```
The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system
```

Replace your own services through `TestBed` providers.

#### Jest example

Expand Down Expand Up @@ -306,15 +312,27 @@ it('shows the signed-out state', () => {

*Applies to the modular API.*

Unlike `Auth`, these cannot be replaced with a plain object. `collection(fakeFirestore, 'items')` throws `Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore`. `ref(fakeStorage, 'file.txt')` throws `Cannot read properties of undefined (reading 'path')`.
Unlike `Auth`, these cannot be replaced with a plain object. `collection(fakeFirestore, 'items')` throws:

```
Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
```

`ref(fakeStorage, 'file.txt')` throws `Cannot read properties of undefined (reading 'path')`.

Do this instead: use [real services with made-up options](#use-real-services-with-made-up-options) when the code only builds references, and [mock the module](#mock-the-module) when it reads data.

### No Firebase App has been created

*Applies to the modular API.*

The full message is `Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app).` Something asked for the default Firebase app and none exists. In a test this has three causes:
The full message is:

```
Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app).
```

Something asked for the default Firebase app and none exists. In a test this has three causes:

- **The code under test calls `getAuth()`, `getFirestore()` or a similar function itself.** Adding `provideFirebaseApp` to the test is not enough, because it creates the app only when something injects `FirebaseApp` or a service that depends on it, such as `Auth`. Do one of these:
- Create the app before creating the component, with `TestBed.runInInjectionContext(() => initializeApp(fakeOptions))`. Configure `TestBed` first, because it cannot be configured after this call.
Expand Down Expand Up @@ -405,7 +423,13 @@ Karma runs the tests in a real browser, and AngularFire needs no extra test conf

*Applies to the modular API.*

The [fake `Auth` object](#give-auth-a-fake-object) works under Jasmine, but the last line of its example does not compile. Jasmine's types check the expected value against `User`, and the build stops with `TS2345: Argument of type '{ uid: string; getIdToken: () => Promise<string>; }' is not assignable to parameter of type 'Expected<User | null>'`. Give `expect` the type `unknown`:
The [fake `Auth` object](#give-auth-a-fake-object) works under Jasmine, but the last line of its example does not compile. Jasmine's types check the expected value against `User`, and the build stops with:

```
TS2345: Argument of type '{ uid: string; getIdToken: () => Promise<string>; }' is not assignable to parameter of type 'Expected<User | null>'
```

Give `expect` the type `unknown`:

```ts
expect<unknown>(await firstValueFrom(component.user$)).toEqual(fakeUser);
Expand Down Expand Up @@ -505,6 +529,6 @@ Three things change after migrating to Vitest:

- The real compat `AngularFireAuth` no longer runs. [Replace the compat service](#replace-a-compat-service) in the tests that use it.
- A cleanup hook written once for the whole Karma run now covers only its own spec file. Two ways to handle it (either works):
- Move it to a file listed in the `setupFiles` option of the `test` target. If using `@angular/build` 21.2, add that file to `include` in `tsconfig.spec.json` as well. Or
- Move it to a file listed in the `setupFiles` option of the `test` target. Add that file to `include` in `tsconfig.spec.json` as well. `@angular/build` 21.2 to 22.1 need it. Or
- Copy it into every spec file that creates an app.
- A module mock can take over the job of a wrapper object. Read the notes under [Mock the module](#mock-the-module) before using `vi.mock`.
Loading
Loading