You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
docs(auth): rewrite the server-side rendering section (#3740)
The old section documented a setup that no longer works: it read the
ID token from an Authorization header via REQUEST with Node property
syntax, and its snippet had five errors that kept it from compiling.
The new section documents the path that works, verified end to end on
a fresh Angular 21 SSR app: RenderMode.Server on the route, a __session
cookie synced to the ID token, the generated server.ts handler replaced
rather than duplicated, and inject(FirebaseApp) passed to every
provider. Each step records what silently breaks without it, because
every omission renders a signed-out page with no error to debug
against.
beforeAuthStateChanged is imported from firebase/auth because the
AngularFire wrapper holds the app unstable until its callback first
runs, which makes ng build fail during route extraction (#3748).
Also corrects the emulator example further down the file.
Fixes#3585
@@ -60,36 +60,220 @@ Update the imports from `import { ... } from 'firebase/auth'` to `import { ... }
60
60
61
61
## Server-side Rendering
62
62
63
-
To support Auth context in server-side rendering, you can provide `FirebaseServerApp`:
63
+
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.
64
+
65
+
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.
66
+
67
+
All 4 steps below are required. Miss any one of them and the page still renders, but it renders signed out, with no error to tell you why.
68
+
69
+
### 1. Serve the route with `RenderMode.Server`
70
+
71
+
`ng new --ssr` scaffolds `app.routes.server.ts` with every route set to `RenderMode.Prerender`. Prerendering runs at build time, so there is no request and no cookie, and Angular provides neither `REQUEST` nor `REQUEST_CONTEXT`. Any route that must already render as the signed-in user before hydration has to be `RenderMode.Server`. A `RenderMode.Client` route renders in the browser, where the user is already signed in, so it needs none of this.
// Must update the cookie before the sign-out completes, otherwise a page
128
+
// load that races it still sends the signed-out user's token.
129
+
priorToken=cookies.get('__session');
130
+
writeSessionCookie(awaituser?.getIdToken());
131
+
},
132
+
() =>writeSessionCookie(priorToken)
133
+
);
134
+
destroyRef.onDestroy(unsubscribe);
135
+
}),
136
+
```
137
+
138
+
The 2 hooks cover different moments:
139
+
-`idToken` fires after an auth state change has completed, and also when Firebase refreshes the token in the background, which is what keeps the cookie current.
140
+
-`beforeAuthStateChanged` fires earlier, while an auth state change is still in progress and before Firebase sets the new user, so a page load that races a sign-out cannot send a token for the user who just left and get their data rendered back. Its third argument puts the cookie back if another blocking callback rejects the auth state change.
141
+
142
+
Name the cookie `__session`. Behind Firebase Hosting it is the [only cookie forwarded](https://firebase.google.com/docs/hosting/manage-cache#using_cookies) to your server code, and any other name is dropped before your app sees it.
143
+
144
+
#### Both attributes matter
145
+
146
+
The cookie sync above sets `{ secure: true, sameSite: 'lax' }`, and neither attribute is optional.
147
+
148
+
-`secure` keeps the cookie off unencrypted connections. Browsers make an exception for `localhost`, so local development still works.
149
+
-`sameSite: 'lax'` keeps the cookie off cross-site requests while still sending it when someone follows a link into your app, which is what lets that first page render signed in. If your app never needs a signed-in first render from an external link, use `'strict'` instead.
150
+
151
+
#### What this cookie carries
152
+
153
+
This cookie carries a short-lived ID token that scripts on your page can read. Firebase already keeps the signed-in state in browser storage, so the cookie does not create a new place for a token to be stolen from, but it does travel on every request.
154
+
155
+
If you need a session the browser cannot read, use Firebase's [session cookies](https://firebase.google.com/docs/auth/admin/manage-cookies) with the Admin SDK instead. Those cannot be handed to `initializeServerApp`, so that approach means verifying the cookie yourself and building your own server-side Auth context.
156
+
157
+
#### `beforeAuthStateChanged` from `firebase/auth`
158
+
159
+
One import in the code above is deliberately different from the rest of this guide. `beforeAuthStateChanged` comes from `firebase/auth` rather than `@angular/fire/auth`. AngularFire's version keeps the app marked as busy until its callback first runs, and this callback only runs when someone signs in or out.
160
+
161
+
Importing it from `@angular/fire/auth` makes `ng build` hang during route extraction and fail with a timeout. That is a bug on our side, tracked in [#3748](https://github.com/angular/angularfire/issues/3748). Once the fix lands, this can be imported from `@angular/fire/auth` like everything else.
The `server.ts` the Angular CLI generated already renders your app for every request that is not a static file. Replace that existing `app.use` block with this one, which reads the cookie and hands the token to the render. Do not add a second block, because the first one to match wins and the token would never arrive:
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.
191
+
192
+
The second argument to `handle` is what the render reads back as `REQUEST_CONTEXT`.
193
+
194
+
### 4. Build the server app from the token
195
+
196
+
In `app.config.ts`, choose the Firebase app based on where the code is running, and pass that app to every Firebase provider:
-**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.
244
+
-**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.
245
+
-**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.
246
+
-**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.
247
+
-**The cast is needed** because Angular types `REQUEST_CONTEXT` as `unknown`.
248
+
249
+
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.
250
+
251
+
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.
252
+
253
+
### Using `REQUEST` instead of a cookie
254
+
255
+
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:
Follow Firebase's [ Session Management with Service Workers documentation](https://firebase.google.com/docs/auth/web/service-worker-sessions) to learn how to pass the `idToken`to the server. __Note: this will not currently work in dev-mode as Angular SSR does not provide a method to get the Request headers.__
276
+
`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.
93
277
94
278
## Convenience observables
95
279
@@ -187,15 +371,15 @@ export class UserComponent implements OnDestroy {
0 commit comments