以 Auth ID 權杖初始化 FirebaseServerApp 例項時,系統會啟用用戶端轉譯 (CSR) 和伺服器端轉譯 (SSR) 環境之間的已驗證使用者工作階段橋接。以含有 Auth ID 權杖的 FirebaseServerApp 物件初始化的 Firebase Auth SDK 執行個體,會在初始化時嘗試登入使用者,應用程式不必叫用任何登入方法。
提供 Auth ID 權杖後,應用程式就能在用戶端使用任何 Auth 登入方法,確保工作階段在伺服器端持續進行,即使是需要使用者互動的登入方法也一樣。此外,這項功能可將需要大量運算的作業卸載至伺服器,例如經過驗證的 Firestore 查詢,應能提升應用程式的算繪效能。
/// Next.jsimport{initializeServerApp}from"firebase/app";import{getAuth}from"firebase/auth";// Replace the following with your app's// Firebase project configurationconstfirebaseConfig={// ...};constfirebaseServerAppSettings={authIdToken:token// See "Pass client tokens to the server side// rendering phase" for an example on how transmit// the token from the client and the server.}constserverApp=initializeServerApp(firebaseConfig,firebaseServerAppSettings);constserverAuth=getAuth(serverApp);// FirebaseServerApp and Auth will now attempt// to sign in the current user based on provided// authIdToken.
/// Next.jsimport{initializeServerApp}from"firebase/app";// Replace the following with your app's// Firebase project configurationconstfirebaseConfig={// ...};constfirebaseServerAppSettings={appCheckToken:token// See "Pass client tokens to the server side// rendering phase" for an example on how transmit// the token from the client and the server.}constserverApp=initializeServerApp(firebaseConfig,firebaseServerAppSettings);// The App Check token will now be appended to all Firebase service requests.
將用戶端權杖傳遞至伺服器端轉譯階段
如要將經過驗證的 Auth ID 權杖 (和 App Check 權杖) 從用戶端傳輸至伺服器端算繪 (SSR) 階段,請使用 Service Worker。這個方法會攔截觸發 SSR 的擷取要求,並將權杖附加至要求標頭。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-05 (世界標準時間)。"],[],[],null,["If you have worked with the Firebase JS SDK or other Firebase client SDKs, you\nare probably familiar with the `FirebaseApp` interface and how to use it to\nconfigure app instances. To facilitate similar operations on the server side,\nFirebase provides `FirebaseServerApp`.\n\n`FirebaseServerApp` is a variant of `FirebaseApp` for use in server-side\nrendering (SSR) environments. It includes tools to continue Firebase sessions\nthat span the client side rendering (CSR) / server-side rendering divide. These\ntools and strategies can help enhance dynamic web apps built with Firebase and\ndeployed in Google environments like [Firebase App Hosting](/docs/app-hosting).\n\nUse `FirebaseServerApp` to:\n\n- Execute server-side code within the *user* context, in contrast to the Firebase Admin SDK which has full administration rights.\n- Enable the use of App Check in SSR environments.\n- Continue a Firebase Auth session that was created in the client.\n\nThe FirebaseServerApp lifecycle\n\nServer-side rendering (SSR) frameworks and other non-browser runtimes such as\ncloud workers optimize for initialization time by reusing resources across\nmultiple executions. `FirebaseServerApp` is designed to accommodate these\nenvironments by using a reference count mechanism. If an app invokes\n`initializeServerApp` with the same parameters as a previous\n`initializeServerApp`, it receives the same `FirebaseServerApp` instance that\nwas already initialized. This cuts down on unnecessary initialization overhead\nand memory allocations. When `deleteApp` is invoked on a `FirebaseServerApp`\ninstance, it reduces the reference count, and the instance is freed after the\nreference count reaches zero.\n\nCleaning up `FirebaseServerApp` instances\n\nIt can be tricky to know when to call `deleteApp` on a `FirebaseServerApp`\ninstance, especially if you are running many asynchronous operations in\nparallel. The `releaseOnDeref` field of the `FirebaseServerAppSettings` helps\nsimplify this. If you assign `releaseOnDeref` a reference to an object with the\nlifespan of the request's scope (for example, the headers object of the SSR\nrequest), the `FirebaseServerApp` will reduce its reference count when the\nframework reclaims the header object. This automatically cleans up your\n`FirebaseServerApp` instance.\n| **Note:** The value `FirebaseServerApp.releaseOnDeref` is not used when `initializeServerApp` checks for an existing `FirebaseServerApp` instance with an identical configuration.\n\nHere's an example usage of `releaseOnDeref`: \n\n /// Next.js\n import { headers } from 'next/headers'\n import { FirebaseServerAppSettings, initializeServerApp} from \"@firebase/app\";\n\n export default async function Page() {\n const headersObj = await headers();\n appSettings.releaseOnDeref = headersObj;\n let appSettings: FirebaseServerAppSettings = {};\n const serverApp = initializeServerApp(firebaseConfig, appSettings);\n ...\n }\n\n| **Note:** Avoid mixing `deleteApp()` calls with instances that were created with `releaseOnDeref`; otherwise apps might be destroyed earlier than intended.\n\nResume authenticated sessions created on the client\n\nWhen an instance of `FirebaseServerApp` is initialized with an Auth ID token, it\nenables bridging of authenticated user sessions between the client-side\nrendering (CSR) and server-side rendering (SSR) environments. Instances of the\nFirebase Auth SDK initialized with a `FirebaseServerApp` object containing an\nAuth ID token will attempt to sign in the user on initialization without the\nneed for the application to invoke any sign-in methods.\n\nProviding an Auth ID token allows apps to use any of Auth's sign-in methods\non the client, ensuring that the session continues on the server-side, even for\nthose sign-in methods that require user interaction. Additionally, it enables\nthe offloading of intensive operations to the server such as authenticated\nFirestore queries, which should improve your app's rendering performance. \n\n /// Next.js\n import { initializeServerApp } from \"firebase/app\";\n import { getAuth } from \"firebase/auth\";\n\n // Replace the following with your app's\n // Firebase project configuration\n const firebaseConfig = {\n // ...\n };\n\n const firebaseServerAppSettings = {\n authIdToken: token // See \"Pass client tokens to the server side\n // rendering phase\" for an example on how transmit\n // the token from the client and the server.\n }\n\n const serverApp =\n initializeServerApp(firebaseConfig,\n firebaseServerAppSettings);\n const serverAuth = getAuth(serverApp);\n\n // FirebaseServerApp and Auth will now attempt\n // to sign in the current user based on provided\n // authIdToken.\n\n| **Note:** Auth instances created with `FirebaseServerApp` don't support operations that log out the current user, sign in a new user, or otherwise replace the current user. Mutations to the Auth user state should be driven by the browser session.\n\nUse App Check in SSR environments\n\nApp Check enforcement relies on an App Check SDK instance that Firebase SDKs use\nto internally call `getToken`. The resulting token is then included in requests\nto all Firebase services, allowing the backend to validate the app.\n\nHowever, because the App Check SDK needs a browser to access specific heuristics\nfor app validation, it can't be initialized in server environments.\n\n`FirebaseServerApp` provides an alternative. If a client-generated App Check\ntoken is provided during `FirebaseServerApp` initialization, it will be used by\nthe Firebase product SDKs when invoking Firebase services, eliminating the need\nfor an App Check SDK instance. \n\n /// Next.js\n import { initializeServerApp } from \"firebase/app\";\n\n // Replace the following with your app's\n // Firebase project configuration\n const firebaseConfig = {\n // ...\n };\n\n const firebaseServerAppSettings = {\n appCheckToken: token // See \"Pass client tokens to the server side\n // rendering phase\" for an example on how transmit\n // the token from the client and the server.\n }\n\n const serverApp =\n initializeServerApp(firebaseConfig,\n firebaseServerAppSettings);\n\n // The App Check token will now be appended to all Firebase service requests.\n\n| **Note:** If the token fails local verification due to expiration or parsing errors, then a console error is logged at the time of initialization of the `FirebaseServerApp` instance.\n\nPass client tokens to the server-side rendering phase\n\nTo transmit authenticated Auth ID tokens (and App Check tokens) from the client\nto the server-side rendering (SSR) phase, use a service worker.\nThis approach involves intercepting fetch requests that trigger SSR and\nappending the tokens to the request headers.\n\nRefer to [Session management with service workers](/docs/auth/web/service-worker-sessions)\nfor a reference implementation of a Firebase Auth service worker. Also see\n[Server side changes](/docs/auth/web/service-worker-sessions#server_side_changes)\nfor code that demonstrates how to parse these tokens from the headers for use in\n`FirebaseServerApp` initialization.\n| **Tip:** Refreshing the tokens within the service worker before appending them to the request headers is a best practice that ensures the SSR phase receives up-to-date credentials."]]