Firebase migration example

When you build a web application, reducing bundle size is essential to improve loading speed and user experience. In that context, Firebase can become a bottleneck because it used to add a large amount of code to the final bundle.

Firebase version 9 introduced the modular API and significantly reduced runtime size. In this article I explain the migration from Firebase 7 to 9 in Angular and show practical examples of the required changes.

You can review the sample code here: https://github.com/al118345/migracion_angular_firebase9 and this video: https://www.youtube.com/watch?v=cpR0NDDWOCw:

1. Optimizing your Angular project

When you start an Angular project, it is easy to keep adding npm packages until the final bundle becomes much larger than expected.

Application size matters for two reasons:

  • Performance: smaller applications start faster, consume fewer resources and reduce bounce rate.
  • Costs: lighter bundles usually reduce infrastructure and delivery costs.

2. Slimming down the application

A practical way to understand what is increasing bundle size is to inspect the generated bundles with webpack-bundle-analyzer.

This tool displays an interactive heatmap so you can see which dependencies take the most space.

To install the library, run:

After that, build the project with the --stats-json option:

This generates a stats.json file.

Then execute the following command, where path_to_stats_file is the path to that file:

The result is the following heatmap:

1. Example result

3. Firebase migration example

Applications using Firebase Web SDK 8 or earlier usually include a very large node_modules footprint.

Firebase package size
1. Firebase size example in version 7

That affects both performance and efficiency. Firebase 9 was designed to improve tree-shaking and reduce shipped code, which makes it a better option for production Angular applications.

Library installation

Install the new version with:
Then remove the following modules from src/app/app.module.ts:

In this example, Firebase credentials are stored in src/environments/environments.prod.ts using this structure:

Once those modules are removed, import the modular libraries directly in the component or service that needs them.

This is a login example in Firebase 7 using email and password:
The equivalent implementation in version 9 is:
If you want to fetch data from Firebase Realtime Database in version 7, you would use:
In version 9, the equivalent code is:
If you use Cloud Firestore, version 7 would look like this:
And the version 9 equivalent is:
Finally, here is an example of Firebase communication where obtener_base_de_datos_realtime() is called synchronously and handled with then/finally: