'Reducing Firebase Bundle Size NextJS

My NextJS bundle size seems to be huge (200-300 kB first load per page). I ran the bundle analyzer, and the culprit seems to be Firebase, which I use for user auth, storing data in Firestore, and calling Firebase functions. I have seen strategies to reduce bundle sizes like using dynamic imports, but I think the issue has more to do with how I am instantiating Firebase. This is what I am doing:

clientApp.ts :

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";

const clientCredentials = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

if (!firebase.apps.length) {
  firebase.initializeApp(clientCredentials);
}
const firebaseFunctions = firebase.functions();
firebaseFunctions.useEmulator("localhost", 5001);

export const auth = firebase.auth();
export const db = firebase.firestore();
export const functions = firebaseFunctions;

AuthContext.tsx :

import React from "react";
import firebase from "firebase/compat/app";

export const AuthContext = React.createContext<firebase.User | null>(null);

_app.tsx :

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { AuthProvider } from "../provider/AuthProvider";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <AuthProvider>
      <div className="h-screen w-screen overflow-y-hidden">
        <Component {...pageProps} />
      </div>
    </AuthProvider>
  );
}

export default MyApp;

Then, I call const user = useContext(AuthContext); in my pages to get the user session data. To use Firestore or functions, I import db or functions from clientApp.ts. Does this make sense or is it ineficiente and contributing to the large bundle size?

I have tried dynamic imports, but either I did not implement them correctly or they are not helpful in this situation.



Solution 1:[1]

You're using the compatibility layer of Firebase's modular SDKs, so that you can run code that uses the older namespaced syntax. Unfortunately using this compatibility layer and syntax prevents your build tool from tree-shaking any unused code.

The solution is to use the newer modular syntax of the SDKs, as shown in the upgrade guide and in all samples in the documentation. I also recommend checking out Deep dive into the new Firebase JS SDK design and The new Firebase JS SDK is now GA on the Firebase blog.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen