Skip to content

Commit 74abd5a

Browse files
feat(app): add initializeBrowserOrServerApp for browser & server apps (#3844)
* feat(app): add initializeBrowserOrServerApp for browser & server apps One call inside provideFirebaseApp that returns the ordinary app in the browser and, on the server, a FirebaseServerApp for the visitor's ID token and App Check token, read from REQUEST_CONTEXT or passed in the settings. With neither token it returns the ordinary app. The server app is released when the render is garbage collected, as the releaseOnDeref setup in the guide does. releaseAfterRender opts into a release at render end or a fixed time after it. A token Firebase cannot parse now renders signed out with one warning instead of an HTTP 500. In dev mode a request with no request context is noted once. The App Check server warning now says which renders send no token. The Node specs can import the built library through a resolve hook. Fixes #3843 * fix(app): keep the default release working when an ngOnDestroy throws The object handed to the SDK as releaseOnDeref was kept alive by a DestroyRef.onDestroy closure. R3Injector.destroy runs every service's ngOnDestroy before it empties those closures, so a throw there left the object reachable from the injector, and any listener that kept the injector alive kept the server app alive with it. The object is now a providedIn: 'root' service, which the finally of destroy drops whatever threw before it. The timed mode still releases from DestroyRef.onDestroy and a throw before it still skips that release, as the docs say. New specs on the release path: the default release observed through forced collections, a shared app with a positive releaseAfterRender released once per render, a null JSON payload, the App Check half of the token comparison, and a throwing ngOnDestroy next to a retained injector reference. The test:node scripts pass --expose-gc for the forced collections. The resolve hook picks the exports entry the way Node does, the first key in the map's order that is an active condition or default. Refs #3844
1 parent cf39fe6 commit 74abd5a

11 files changed

Lines changed: 908 additions & 8 deletions

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
"test:firefox-headless": "npx --yes firebase-tools@latest emulators:exec --project=demo-123 \"ng test --watch=false --browsers=FirefoxHeadless\"",
1818
"lint": "ng lint",
1919
"lint:fix": "ng lint --fix",
20-
"test:node": "node -r tsconfig-paths/register ./dist/out-tsc/jasmine/tools/jasmine.mjs --input-type=commonjs",
21-
"test:node-esm": "node -r tsconfig-paths/register ./dist/out-tsc/jasmine/tools/jasmine.mjs",
20+
"test:node": "node --expose-gc --import ./tools/jasmine-register-angular-fire.mjs -r tsconfig-paths/register ./dist/out-tsc/jasmine/tools/jasmine.mjs --input-type=commonjs",
21+
"test:node-esm": "node --expose-gc --import ./tools/jasmine-register-angular-fire.mjs -r tsconfig-paths/register ./dist/out-tsc/jasmine/tools/jasmine.mjs",
2222
"test:typings": "node ./tools/run-typings-test.js",
2323
"test:build": "bash ./test/ng-build/build.sh",
2424
"test:all": "npm run test:node-esm && npm run test:chrome-headless && npm run test:typings && npm run test:build",

‎src/app-check/app-check.module.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,17 @@ const isLocalhost = typeof window !== 'undefined' && LOCALHOSTS.includes(window.
3939

4040
let warnedServerSkip = false;
4141

42+
/** Resets the server-rendering warning for specs, which share one process. */
43+
export const ɵresetAppCheckServerWarning = (): void => {
44+
warnedServerSkip = false;
45+
};
46+
4247
export function appCheckInstanceFactory(fn: (injector: Injector) => FirebaseAppCheck) {
4348
return (zone: NgZone, injector: Injector, platformId: unknown) => {
4449
if (isPlatformServer(platformId) && !injector.get(APP_CHECK_ON_SERVER)) {
4550
if (isDevMode() && !warnedServerSkip) {
4651
warnedServerSkip = true;
47-
console.warn("AngularFire skips App Check during server rendering, so server-side Firebase requests carry no App Check token. To run App Check there, provide APP_CHECK_ON_SERVER as true in your server config. Find more at https://github.com/angular/angularfire/blob/main/docs/app-check.md");
52+
console.warn("AngularFire skips App Check during server rendering, so server renders without a relayed App Check token send none. To relay the browser's App Check token, build the app with initializeBrowserOrServerApp and hand the token to the render as the appCheckToken key of the request context. To run App Check on the server instead, provide APP_CHECK_ON_SERVER as true in your server config. Find more at https://github.com/angular/angularfire/blob/main/docs/app-check.md");
4853
}
4954
return undefined;
5055
}

‎src/app-check/app-check.spec.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { PLATFORM_ID, PendingTasks } from '@angular/core';
22
import { TestBed } from '@angular/core/testing';
33
import { FirebaseApp, deleteApp, getApp, initializeApp, provideFirebaseApp } from '@angular/fire/app';
4-
import { APP_CHECK_ON_SERVER, AppCheck, CustomProvider, initializeAppCheck, onTokenChanged, provideAppCheck } from '@angular/fire/app-check';
4+
import { APP_CHECK_ON_SERVER, AppCheck, CustomProvider, initializeAppCheck, onTokenChanged, provideAppCheck, ɵresetAppCheckServerWarning } from '@angular/fire/app-check';
55
import { Auth, connectAuthEmulator, getAuth, provideAuth } from '@angular/fire/auth';
66
import { COMMON_CONFIG } from '../test-config';
77
import { rando } from '../utils';
@@ -54,6 +54,39 @@ describe('AppCheck', () => {
5454
beforeEach(() => {
5555
appName = rando();
5656
setupCalls = 0;
57+
ɵresetAppCheckServerWarning();
58+
});
59+
60+
const configureServerPlatform = () => {
61+
TestBed.configureTestingModule({
62+
providers: [
63+
{ provide: PLATFORM_ID, useValue: 'server' },
64+
provideFirebaseApp(() => initializeApp(COMMON_CONFIG, appName)),
65+
provideTestAppCheck(),
66+
],
67+
});
68+
};
69+
70+
it('warns once during server rendering, saying what a relayed token changes', () => {
71+
const warn = spyOn(console, 'warn');
72+
configureServerPlatform();
73+
TestBed.inject(AppCheck);
74+
expect(warn).toHaveBeenCalledTimes(1);
75+
const message = warn.calls.argsFor(0).join(' ');
76+
expect(message).toContain('server renders without a relayed App Check token send none');
77+
expect(message).toContain('APP_CHECK_ON_SERVER');
78+
expect(message).toContain('initializeBrowserOrServerApp');
79+
});
80+
81+
it('warns once per process, not once per render', () => {
82+
const warn = spyOn(console, 'warn');
83+
configureServerPlatform();
84+
TestBed.inject(AppCheck);
85+
TestBed.resetTestingModule();
86+
appName = rando();
87+
configureServerPlatform();
88+
TestBed.inject(AppCheck);
89+
expect(warn).toHaveBeenCalledTimes(1);
5790
});
5891

5992
it('should skip App Check during server rendering by default', () => {

‎src/app-check/public_api.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
export { AppCheck, appCheckInstance$, AppCheckInstances } from './app-check';
2-
export { provideAppCheck, AppCheckModule, APP_CHECK_ON_SERVER } from './app-check.module';
2+
export { provideAppCheck, AppCheckModule, APP_CHECK_ON_SERVER, ɵresetAppCheckServerWarning } from './app-check.module';
33
export * from './firebase';

‎src/app/app.spec.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { PendingTasks } from '@angular/core';
22
import { TestBed } from '@angular/core/testing';
3-
import { FirebaseApp, deleteApp, initializeApp, onLog, provideFirebaseApp } from '@angular/fire/app';
3+
import { FirebaseApp, deleteApp, getApp, initializeApp, initializeBrowserOrServerApp, onLog, provideFirebaseApp } from '@angular/fire/app';
44
import { COMMON_CONFIG } from '../test-config';
55
import { rando } from '../utils';
66

@@ -55,4 +55,20 @@ describe('FirebaseApp', () => {
5555

5656
});
5757

58+
describe('initializeBrowserOrServerApp', () => {
59+
60+
// The default app is shared with other specs that build it from COMMON_CONFIG, so no other settings and no deleteApp here.
61+
it('returns the default app in the browser whatever tokens it is given', () => {
62+
TestBed.configureTestingModule({
63+
providers: [
64+
provideFirebaseApp(() => initializeBrowserOrServerApp(COMMON_CONFIG, { authIdToken: 'h.e.s', appCheckToken: 'h.e.s' })),
65+
],
66+
});
67+
const browserApp = TestBed.inject(FirebaseApp);
68+
expect(browserApp).toBe(getApp());
69+
expect('settings' in browserApp).toBeFalse();
70+
});
71+
72+
});
73+
5874
});

‎src/app/app.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import { concatMap, distinct } from 'rxjs/operators';
1212
// back when we constructed our own class. Then in the "new class" we just return the FirebaseApp in the
1313
// constructor, this also has the added benefit of Firebase methods taking our DI class without
1414
// casting. E.g,
15-
// constructor(private app: FirebaseApp) { }
16-
// ngOnDestroy() { deleteApp(this.app); }
15+
// private readonly app = inject(FirebaseApp);
16+
// readonly firestore = getFirestore(this.app);
1717
//
1818

1919
export interface FirebaseApp extends IFirebaseApp {}

0 commit comments

Comments
 (0)