Upgrade from the namespaced API to the modular application Stay organized with collections Save and categorize content based on your preferences.
Apps using any namespaced Firebase web API, from thecompat librariesback through version 8 or earlier, should considermigrating to the modular API using the instructions in this guide.
This guide assumesthat you are familiar with the namespaced API and that you will take advantage of amodule bundler such aswebpack orRollup for upgrading andongoing modular app development.
Using a module bundler in your development environment is stronglyrecommended. If you don't use one, you won't be able to take advantage ofthe modular API's main benefits in reduced app size. You'll neednpm oryarn to install the SDK.
The upgrade steps in this guide will be based around an imaginary web app thatuses theAuthentication andCloud Firestore SDKs. By working through the examples, youcan master the concepts and practical steps required to upgrade all supportedFirebase web SDKs.
About the namespaced (compat) libraries
There are two types of libraries available for the Firebase web SDK:
- Modular - a new API surface designed to facilitate tree-shaking(removal of unused code) tomake your web app as small and fast as possible.
- Namespaced (
compat) - a familiar API surface which is fullycompatible with theearlier versions of the SDK, allowing you to upgrade without changing allof your Firebase code at once. Compat libraries have little tono size or performanceadvantages over their namespaced counterparts.
This guide assumes that you will take advantage of the compatlibraries to facilitate your upgrade. These libraries allow you to continueusing namespaced code alongside code refactored for the modular API. This means youcan compile and debug your app more easily as you work through the upgradeprocess.
Keep in mind: the compat libraries are a temporarysolution that will be removed completely in a future major SDK version (suchas version 10 or version 11). Your ultimate goal is to remove compat codeand keep only the modular-style code in your app.For apps with a very small exposure to the Firebase web SDK—for example,an app that makes only a simple call to theAuthentication APIs—it may bepractical to refactor older namespaced code without using the compat libraries.If you are upgrading such an app, you can follow the instructions in this guidefor "the modular API" without using the compat libraries.
About the upgrade process
Each step of the upgrade process is scoped so that you can finish editing thesource for your app and then compile and run it without breakage. In summary,here's what you'll do to upgrade an app:
- Add the modular libraries and the compat libraries to your app.
- Update import statements in your code to compat.
- Refactor code for a single product (for example,Authentication) tothe modular style.
- Optional: at this point, remove theAuthentication compat library and compat codeforAuthentication in order torealize the app size benefit forAuthentication before continuing.
- Refactor functions for each product (for example,Cloud Firestore,FCM, etc.) to the modular style, compiling andtesting until all areas are complete.
- Update initialization code to the modular style.
- Remove all remaining compat statements and compat code fromyour app.
Get the latest version of the SDK
To get started, get the modular libraries and compat libraries using npm:
npmifirebase@12.9.0# ORyarnaddfirebase@12.9.0
Update imports to compat
In order to keep your code functioning after updating your dependencies,change your import statements to use the "compat"version of each import. For example:
Before: version 8 or earlier
importfirebasefrom'firebase/app';import'firebase/auth';import'firebase/firestore';After: compat
// compat packages are API compatible with namespaced codeimportfirebasefrom'firebase/compat/app';import'firebase/compat/auth';import'firebase/compat/firestore';Refactor to the modular style
While the namespaced APIs are based on a dot-chained namespace and servicepattern, the modular approach means that your code will be organizedprincipally aroundfunctions. In the modular API, thefirebase/app package andother packages do not return a comprehensive export that contains all themethods from the package. Instead, the packages export individual functions.
In the modular API, services are passed as the first argument, and the function thenuses the details of the service to do the rest. Let's examine how this works intwo examples that refactor calls to theAuthentication andCloud Firestore APIs.
Example 1: refactoring anAuthentication function
Before: compat
The compat code is identical to the namespaced code, but the importshave changed.
importfirebasefrom"firebase/compat/app";import"firebase/compat/auth";constauth=firebase.auth();auth.onAuthStateChanged(user=>{// Check for user status});After: modular
ThegetAuth function takesfirebaseApp as its first parameter.TheonAuthStateChangedfunction is not chained from theauth instance as it would bein the namespaced API; instead, it's a freefunction which takesauth as its first parameter.
import{getAuth,onAuthStateChanged}from"firebase/auth";constauth=getAuth(firebaseApp);onAuthStateChanged(auth,user=>{// Check for user status});Update handling of Auth methodgetRedirectResult
Caution: If your app uses the Auth methodgetRedirectResult, you must make the updates described in this section. Failure to refactor your codecould result in unpredictable app behavior.The modular API introduces a breaking change ingetRedirectResult. When no redirect operation is called, the modular API returnsnull as opposed to the namespaced API, which returned aUserCredential with anull user.
Before: compat
constresult=awaitauth.getRedirectResult()if(result.user===null &&result.credential===null){returnnull;}returnresult;After: modular
constresult=awaitgetRedirectResult(auth);// Provider of the access token could be Facebook, Github, etc.if(result===null||provider.credentialFromResult(result)===null){returnnull;}returnresult;Example 2: refactoring aCloud Firestore function
Before: compat
import"firebase/compat/firestore"constdb=firebase.firestore();db.collection("cities").where("capital","==",true).get().then((querySnapshot)=>{querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});}).catch((error)=>{console.log("Error getting documents: ",error);});After: modular
ThegetFirestore function takesfirebaseApp as its first parameter, whichwas returned frominitializeApp in an earlier example. Note how thecode to form a query is very different in the modular API; there is no chaining, andmethods such asquery orwhere are now exposed as free functions.
import{getFirestore,collection,query,where,getDocs}from"firebase/firestore";constdb=getFirestore(firebaseApp);constq=query(collection(db,"cities"),where("capital","==",true));constquerySnapshot=awaitgetDocs(q);querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});Update references to FirestoreDocumentSnapshot.exists
Caution: If your app uses theDocumentSnapshot.exists property, you mustperform the update described in this section. Failure to refactor your codecould result in unpredictable app behavior.The modular API introduces a breaking change in which the propertyfirestore.DocumentSnapshot.exists has been changed to amethod. Thefunctionality is essentially the same (testing whether a document exists)but you must refactor your code to use the newer method as shown:
Before:compat
if(snapshot.exists){console.log("the document exists");}After: modular
if(snapshot.exists()){console.log("the document exists");}Example 3: combining namespaced and modular code styles
Using the compat libraries during upgrade allows you to continue using namespacedcode alongside code refactored for the modular API. This means you can keepexisting namespaced code forCloud Firestore while you refactorAuthenticationor other Firebase SDK code tothe modular style, and still successfully compile your app with both codestyles. The same is true for namespaced and modular API codewithin a product suchasCloud Firestore; new and old code styles can coexist, as long as you areimporting the compat packages:
importfirebasefrom'firebase/compat/app';import'firebase/compat/firestore';import{getDoc}from'firebase/firestore'constdocRef=firebase.firestore().doc();getDoc(docRef);Keep in mind that, although your app will compile, you won't get the app sizebenefits of the modular code until you fully remove the compat statements andcode from your app.
Update initialization code
Update your app's initialization code to use modular syntax. It isimportant to update this codeafter you have completed refactoring all thecode in your app; this is becausefirebase.initializeApp() initializes globalstate for both the compat and modular APIs, whereas the modularinitializeApp() function initializes only the state for modular.
Before: compat
importfirebasefrom"firebase/compat/app"firebase.initializeApp({/* config */});After: modular
import{initializeApp}from"firebase/app"constfirebaseApp=initializeApp({/* config */});Remove compat code
To realize the size benefits of the modular API, you should eventuallyconvert all invocations to the modular style shown above and remove all of theimport "firebase/compat/* statements from your code. When you are done, thereshould be no more references to thefirebase.* global namespace or any othercode in the namespaced API style.
Using the compat library from the window
The modular API is optimized to work with modules rather than the browser'swindow object. Previous versions of the library allowed the loading andmanagement of Firebase by using thewindow.firebase namespace. This is notrecommended going forward as it does not allow for unused code elimination.However, the compat version of the JavaScript SDK does work with thewindowfor developers who prefer not to immediately begin the modular upgrade path.
<scriptsrc="https://www.gstatic.com/firebasejs/12.9.0/firebase-app-compat.js"></script><scriptsrc="https://www.gstatic.com/firebasejs/12.9.0/firebase-firestore-compat.js"></script><scriptsrc="https://www.gstatic.com/firebasejs/12.9.0/firebase-auth-compat.js"></script><script>constfirebaseApp=firebase.initializeApp({/* Firebase config */});constdb=firebaseApp.firestore();constauth=firebaseApp.auth();</script>The compatibility library uses modular code under the hood andprovides it with the same API as the namespaced API; this means you canrefer to thenamespaced API referenceand namespaced code snippets for details. This method is notrecommended for long term use, but as a start to upgrade to the fully modularlibrary.
Benefits and limitations of the modular SDK
The fully modularized SDK has these advantages over earlier versions:
- The modular SDK enables a dramatically reduced app size.It adopts the modern JavaScriptModule format, allowing for "tree shaking" practices in which you importonly the artifacts your app needs. Depending on your app,tree-shaking with the modular SDK can result in 80% less kilobytes than acomparable app built using the namespaced API.
- The modular SDK will continue to benefit from ongoing feature development,while the namespaced API will not.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-05 UTC.