# Migrate a React App to the Firebase Modular SDK

Yes. The agent moves a namespaced Firebase 7 or 8 app to the modular API in two builds, compat imports first, and rewrites each listener to unsubscribe properly.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-to-firebase-modular-sdk/firebase/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent finds every place the namespaced API is touched, including the places it leaks to. In an app like bezkoder/react-firebase-database-crud, `package.json` has `firebase` ^7.17.2 and the lockfile resolves it to 7.17.2, on React 16.13.1 and `react-scripts` 3.4.2. `src/firebase.js` opens with `import * as firebase from "firebase"`, which pulls in the entire SDK, adds `firebase/database`, calls `initializeApp` with a config whose `apiKey`, `messagingSenderId` and `appId` are the placeholder `xxx`, and exports `firebase.database()`. `src/services/tutorial.service.js` builds a reference with `.ref("/tutorials")` and wraps `push`, `child(key).update`, `child(key).remove()` and `remove()`. Its `getAll()` returns the reference itself, so the chained API escapes the service: `tutorials-list.component.js` calls `.on("value", this.onDataChange)` when it mounts and `.off("value", this.onDataChange)` when it unmounts.

It upgrades in two steps, each proven by a build. First it installs the current SDK and builds without touching code, to show the starting point: the bare `firebase` entry no longer exists, and Create React App stops with a module-not-found error for it in `src/firebase.js`. Step one is the compat layer. Two import lines change, to a default import from `firebase/compat/app` and a side-effect import of `firebase/compat/database`, and the app compiles again with every call site untouched. This step is worth its own commit. It is small enough to review in a minute, it can be deployed alone, and it already removes the namespace import that dragged every Firebase product into the bundle.

Step two is the modular API. `src/firebase.js` becomes `initializeApp` from `firebase/app` and `getDatabase` from `firebase/database`. In the service, methods on a reference become functions that take one: `ref(database, "/tutorials")`, `push(ref, value)`, `update(child(ref, key), value)`, `remove(child(ref, key))`. The listener is the part that cannot be translated line for line. A modular reference has no `.on` method. `onValue(ref, callback)` returns a function that removes the listener, and that function replaces the `off` call. The agent changes the service to expose `subscribe(callback)` and return that function; the component stores it at mount and calls it at unmount. The snapshot handed to the callback keeps `forEach`, `key` and `val()`, so `onDataChange` does not change.

Building proves the imports, not the behaviour, and the committed config cannot reach a database. The repository has no tests either. So the agent runs the Realtime Database emulator from `firebase-tools` under a `demo-` project id, which needs no credentials, installs the JDK the emulator requires, and points the SDK at it with `connectDatabaseEmulator`. A short Node script then drives the rewritten service: subscribe, create two records, update one, delete one, delete all, unsubscribe, and assert what the listener saw after each write. The same script runs against the compat commit first, so the two steps are shown to behave alike. Builds on Node 17 or later use `NODE_OPTIONS=--openssl-legacy-provider`, since this `react-scripts` bundles with webpack 4.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "codex",
  "input": "Migrate this React app from the namespaced Firebase JavaScript SDK to the modular API. Read package.json, the lockfile, the file that initializes Firebase, every service that wraps it and every component that calls Firebase methods directly or through a returned reference; list each call with its file and line and which Firebase product it belongs to. Install the latest firebase and run the build before changing code, and quote the error. Step one, in its own commit: switch to the compat entry points with the fewest import changes that make the build pass, changing no call site. Step two, in a second commit: rewrite initialization and every call to the modular functions. For each realtime listener, use the function form that returns an unsubscribe function, keep that function, and call it wherever the old code detached the listener; do not leave any code that calls methods on a reference. Keep the service's method names where their meaning is unchanged, and change the interface only where the chained API leaked out, saying which callers changed. Do not put real credentials in the repository and do not change the committed config values. To verify behaviour, install firebase-tools and what it requires, start the emulator for the products this app uses under a demo project id, connect the SDK to it in a script that is not part of the app bundle, and run the same create, read, update, delete and listener checks against the compat commit and the modular commit. Run the production build after each commit and report the bundle sizes it prints. Open a pull request with the call inventory, both builds, the emulator script's output for both commits, and anything you could not verify.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request has two commits that a team can merge together or one at a time. The first changes `package.json`, the lockfile and two lines of `src/firebase.js`. The second rewrites `src/firebase.js` and `src/services/tutorial.service.js` and edits the mount and unmount methods of `tutorials-list.component.js`. The add and edit components do not appear in the diff, because the service methods they call keep their names and still return promises.

The description starts with the call inventory and then shows three builds: the failure on the new SDK with unchanged code, the compat build and the modular build, each with the file sizes Create React App prints. For an app that uses a single product, most of the size reduction arrives with the first commit, when the import of the whole SDK disappears, and the second commit adds less. The pull request reports the figures as printed so nobody has to take that on trust.

The emulator output is what a reviewer should weigh. It lists, for each commit, what the listener received after every write and that nothing arrived after unsubscribing. The remaining risk is stated plainly: the checks ran against the emulator, not your project, and security rules were not exercised. The verification script and the emulator config are added under a directory outside `src`, so they are available for the next upgrade without shipping in the bundle.

## Run it on every app still on the namespaced Firebase SDK

If several apps share this pattern, start one run for each. Search your organisation's code for `import firebase from` and `import * as firebase from`, and for every repository found send `POST /o/{org}/sessions` with its URL in `resources` and the same `input`. Apps that use Auth, Firestore or Storage as well take the same two steps; the prompt already asks the agent to inventory products and start only the emulators that app needs.

The calls return at once with `202` and the session, and a key runs at most `max_concurrent` of them at a time, with the rest waiting as `queued`. Read each result from `GET /o/{org}/sessions/{id}` when its `status` is `completed`: the answer ends with the pull request and the list of anything the agent could not verify, which tells you where to spend review time.

## Why run it on Rush?

A listener rewrite is only shown correct by writing data and watching what the listener receives, and after unsubscribing, what it does not. That takes a running database. The agent starts an emulator in its sandbox, so no test record ever touches a real project and no service account or API key has to be handed over for the run. The emulator's output and the script's assertions are kept in the session's transcript beside the build logs.

The two-commit shape also depends on running things. Claiming that the compat step is behaviour-neutral is cheap; the run backs it by executing one script against both commits on the same machine. If the reviewer wants a third commit, for example moving the config into environment variables, a follow-up message to the session continues in the same sandbox with the emulator tooling already installed.

## Frequently asked questions

### Why not go directly to the modular API?

You can, and in a small app the second commit could be the only one. The compat step exists because it is nearly free, fixes the build on a current SDK, and gives a point to deploy and roll back to. In a large app it also lets teams convert one product or one screen at a time while the rest stays on compat imports.

### Do my data and security rules need to change?

No. The modular API is a different way to call the same services, and data paths, snapshots and rules are unaffected. The agent changes client code only and does not deploy rules or touch the Firebase console.

### Does this work for Firestore and Auth too?

Yes, the same two steps apply: compat imports first, then functions such as `getFirestore`, `collection`, `onSnapshot` and `getAuth`. Listeners there also return an unsubscribe function. The agent inventories which products an app uses and starts the matching emulators for verification.

### Will it need my Firebase credentials?

No. Verification runs against the local emulator under a demo project id. If your config lives in environment variables, the agent leaves them as they are and builds with placeholder values.

## More jobs like this: Upgrade dependencies weekly

- [Upgrade a Project to Prisma 7](https://getrush.ai/run/migrate-to-prisma-7/prisma/)
- [Replace the toml Package With Python's Built-In tomllib](https://getrush.ai/run/migrate-toml-to-tomllib/toml/)
- [Migrate golang.org/x/exp/slices and maps to the Go Standard Library](https://getrush.ai/run/migrate-x-exp-slices-to-slices/golang-x-exp/)
- [Migrate golang.org/x/net/context to the Standard Library context Package in Go](https://getrush.ai/run/migrate-x-net-context-to-context/x-net-context/)
- [Pin Docker Base Images by Digest](https://getrush.ai/run/pin-image-versions/docker/)
- [Pin and Upgrade Container Images in Docker Compose](https://getrush.ai/run/pin-image-versions/docker-compose/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
