Skip to content

Support mono-repos in deployment #653

Open

Description

@laurenzlong

See: firebase/firebase-functions#172

Version info

3.17.3

Steps to reproduce

Expected behavior

Actual behavior

Activity

  1. dinvlad commented on Feb 22, 2018

    @dinvlad

    This seems to work in my setup, i.e. deploy picks up packages from the root node_modules, even though package.json for that is located under the api/ workspace (I've used a different folder name instead of functions/). Is there anything else that needs fixing here?

    EDIT: Moreover, I copy package.json into api/dist to be used by deploy.

    // firebase.json
      ...
      "functions": {
        "source": "api/dist"
      },
      ...
    

    So, 2 levels of nesting still resolve the root node_modules successfully.

  2. orouz commented on Apr 23, 2018

    @orouz

    @dinvlad could you share a repo?

  3. dinvlad commented on Apr 23, 2018

    @dinvlad

    @orouz unfortunately not yet, it's closed source for now.

  4. audkar commented on Jun 17, 2019

    @audkar

    Does anyone managed to tackle this problem? Sharing simple example project would be very useful.

  5. jthegedus commented on Jun 17, 2019

    @jthegedus
    Contributor

    @audkar Currently I just use lerna.js.org and it's run command to execute an npm script in each subfolder with this folder structure:

    - service1/
    |  - .firebaserc
    |  - firebase.json
    - service2/
    |  - .firebaserc
    |  - firebase.json
    - app1/
    |  - .firebaserc
    |  - firebase.json
    - app2/
    |  - .firebaserc
    |  - firebase.json
    - firestore/
    |  - firestore.rules
    |  - firestore.indexes.json
    - etc...
    

    Ensuring the firebase.json files for each service don't stomp on one another is left up to the user. Simple conventions of using function groups and multi-site name targeting means this is solved for Cloud Functions and Hosting. Still haven't got a solution for Firestore/GCS rules yet, though splitting them up may not be ideal...

    discussed here previously - #1116

  6. audkar commented on Jun 18, 2019

    @audkar

    @jthegedus thank you for your reply. But I think issue of this ticket is different. I am trying to use yarn workspaces. And seems that firebase tools doesn't pickup symlink dependencies when uploading functions

  7. jthegedus commented on Jun 18, 2019

    @jthegedus
    Contributor

    Ah fair enough, I've avoided that rabbit hole myself

  8. dinvlad commented on Jun 18, 2019

    @dinvlad

    Could you elaborate what the issue is? As mentioned above, I just use bare Yarn with api and app workspaces in it, and I build them using yarn workspace api build && yarn workspace app build (with build script specific to each workspace). The build scripts

    1. compile TS code with outDir into api/dist and app/dist respectively
    2. copy the corresponding package.json files into dist directories
    3. copy yarn.lock from the root folder, into dist directories

    Then I just run yarn firebase deploy from the root folder, and it picks up both api/dist and app/dist without any hiccups. My firebase.json looks like

      "functions": {
        "source": "api/dist"
      },
      "hosting": {
        "public": "app/dist",

    Unfortunately, I still can’t share the full code, but this setup is all that matters, afaik.

  9. dinvlad commented on Jun 18, 2019

    @dinvlad

    Also, I might be wrong but I think the firebase deploy script doesn’t actually use your node_modules directory. I think it just picks up the code, package.json, and yarn.lock from the dist directories, and does the rest.

  10. samtstern commented on Jun 18, 2019

    @samtstern
    Contributor
  11. jthegedus commented on Jun 18, 2019

    @jthegedus
    Contributor

    @dinvlad Yes, it requires the package.json and whichever lock file you use as it installs deps in the cloud post deployment.

    I believe the scenario originally outlined in the other issue was using a shared package within the workspace and some issues with scope-hoisting. As I was not using yarn this way I can only speculate from what I have read there.

  12. dinvlad commented on Jun 18, 2019

    @dinvlad

    @samtstern @jthegedus thanks, good to know!

  13. audkar commented on Jun 18, 2019

    @audkar

    Seems we all talk about different problems. I will try to describe yarn workspaces problem.

    Problematic project

    project layout

    - utilities/
    |  - package.json
    - functions/
    |  - package.json
    - package.json
    

    ./package.json

    {
      "private": true,
      "workspaces": ["functions", "utilities"]
    }
    

    functions/package.json

    {
      <...>
      "dependencies": {
        "utilities": "1.0.0",
        <...>
      }
    }
    

    Problem

    Error during function deployment:

    Deployment error.
    Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`gen_package_lock` had stderr output:\nnpm WARN deprecated [email protected]: use String.prototype.padStart()\nnpm ERR! code E404\nnpm ERR! 404 Not Found: [email protected]\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2019-06-18T07_10_42_472Z-debug.log\n\nerror: `gen_package_lock` returned code: 1", "errorType": "InternalError", "errorId": "1971BEF9"}}
    

    Functions works fine locally on emulator.

    Solutions tried

    Uploading node_modules (using functions.ignore in firebase.json). Result is same.

    My guess that it is because utilities is created as syslink in node-modules node_modules/utilities -> ../../utilities

    Could it be that firebase-tools doesn't include content of symlink'ed modules when uploading (no dereferencing)?

  14. dinvlad commented on Jun 18, 2019

    @dinvlad

    Sorry, could you clarify which folder your firebase.json lives in (and show its configuration section for functions)?

  15. 174 remaining items

  16. Sandbye commented on Oct 23, 2025

    @Sandbye

    bump

  17. ivliag commented on Dec 12, 2025

    @ivliag

    Managed to solve this with build output approach with Rollup. Not ideal, but can't think of a better solution given the limitations.

    The Strategy

    Instead of fighting Firebase Tools' symlink handling, we bundle all local workspace packages into the deployment artifact and strip them from package.json entirely.

    Implementation Overview

    1. Monorepo Structure

    /apps/firefunctions/        # Firebase Functions app
    /pkgs/js/utils/             # Local workspace packages
    

    2. Rollup Configuration

    Create apps/firefunctions/rollup.config.mjs with a three-step process:

    Step 1: Tell Rollup to BUNDLE local packages (not externalize them)

    import nodeExternals from 'rollup-plugin-node-externals';
    
    export default {
      plugins: [
        nodeExternals({
          builtins: true,
          deps: true,
          devDeps: false,
          peerDeps: true,
          optDeps: true,
          exclude: /^@your-scope\//,  // Don't externalize - bundle these instead!
        }),
        // ... other plugins
      ],
    };

    Step 2: Strip local packages from the output package.json

    import * as fs from 'fs/promises';
    import * as path from 'path';
    
    const DIST_DIR = './dist';
    
    const copyPackageJson = () => ({
      name: 'copy-package-json',
      async writeBundle() {
        const packageJsonContent = await fs.readFile('./package.json', 'utf-8');
        const packageJson = JSON.parse(packageJsonContent);
    
        // Remove all local workspace dependencies
        if (packageJson.dependencies) {
          Object.keys(packageJson.dependencies).forEach(dep => {
            if (dep.startsWith('@your-scope/')) {
              delete packageJson.dependencies[dep];
            }
          });
        }
    
        if (packageJson.devDependencies) {
          Object.keys(packageJson.devDependencies).forEach(dep => {
            if (dep.startsWith('@your-scope/')) {
              delete packageJson.devDependencies[dep];
            }
          });
        }
    
        await fs.writeFile(
          path.join(DIST_DIR, 'package.json'),
          JSON.stringify(packageJson, null, 2)
        );
      },
    });

    Step 3: Configure TypeScript to compile everything

    import typescript from '@rollup/plugin-typescript';
    
    export default {
      plugins: [
        typescript({
          tsconfig: './tsconfig.json',
          sourceMap: true,
          declaration: false,
          declarationMap: false,
          // Override include to process all TypeScript files including workspace packages
          include: ['**/*.ts', '**/*.tsx'],
          compilerOptions: {
            outDir: path.join(DIST_DIR, 'src'),
          },
        }),
        // ... other plugins
      ],
    };

    Complete Rollup Config Example

    3. Firebase Configuration

    Point firebase.json to the built output:

    {
      "functions": {
        "source": "apps/firefunctions/dist"
      }
    }

    4. Package.json Scripts and Main

    Add build scripts to your apps/firefunctions/package.json and don't forget to set main parameter to the src/index.js which will be related to the dist folder after build completes:

    {
      "scripts": {
        "build": "rollup -c rollup.config.mjs",
        "deploy": "yarn build && firebase deploy --only functions"
      },
      "main": "src/index.js",
    }

    5. Firebase.json Source

    Set source in firebase.json to the dist folder:

    {
      "functions": [{
        "source": "./dist"
      }]
    }

    Result

    The dist/ folder contains:

    • Compiled JavaScript with all local packages bundled in
    • package.json with ONLY external npm dependencies

    Overall benefits:

    • ✅ You can import local workspace packages seamlessly
    • ✅ Functions can be deployed either from root or from within apps/firefunctions

    Hope this helps.

  18. kdawgwilk commented on Dec 12, 2025

    @kdawgwilk
    Contributor

    @ivliag Are you also stripping the local deps from the lockfile?

  19. ivliag commented on Dec 12, 2025

    @ivliag

    @kdawgwilk lockfile stays in the repository root so it doesn't get to the dist folder at therefore doesn't get deployed.
    Again, not ideal, but I do --save-exact for all the packages I install, so shouldn't be that critical.

  20. kdawgwilk commented on Dec 13, 2025

    @kdawgwilk
    Contributor

    @ivliag Ah --save-exact will only save the exact version of the top level dep you actually use but the transitive downstream deps will still get updated out from under you when the cloud build happens. So like the recent Shai Hulud your container builds would be pulling new vulnerable transitive dep versions into the container at build time 😬

  21. x1z7 commented on Apr 2, 2026

    @x1z7

    This issue basically makes firebase cloud functions a terrible backend solution in any serious project. If only they would spend less time building AI slops and more time implementing crucial features like this one, maybe then they would have a real positive impact.

  22. johnnyoshika commented on Apr 2, 2026

    @johnnyoshika

    Has anyone tried either of these packages in their monorepo:

    https://github.com/0x80/isolate-package
    https://github.com/0x80/firebase-tools-with-isolate

    ...to get around the lock file issue with deploying to Firebase when there's only a single root package-lock.json and not a firebase function specific package-lock.json? With the recent axios trojan attack, it's a good reminder that we need to lock down our package versions, but Firebase inside a npm monorepo doesn't make that easy. I wonder if either of those packages listed above solves the problem.

  23. x1z7 commented on Apr 3, 2026

    @x1z7

    @johnnyoshika I would say the isolate fork is the best solution for the time being, since it doesn't break the emulator live updates and it handles the lock file.
    But using an unofficial fork that doesn't seem to be synced up with the upstream on a regular basis, is not that great. Not to mention that it adds complexity, which goes against the whole point of using a monorepo, which is to simplify dependency management and improve code sharing.
    After spending a couple of days trying out different solutions I decided to remove the functions package from the monorepo. Will probably use something like quicktype + chokidar to automatically generate different backend & frontend models/schemas from a single source of truth.

  24. kdawgwilk commented on Apr 3, 2026

    @kdawgwilk
    Contributor

    we have our own fork that we use AskElephant/firebase-tools that uses a couple ideas from the isolate package changes and supports pnpm because thats what we use. We also fixed a bunch of bugs with quota rate limits that were causing us all kinds of problems with deploys at scale that we tried to get merged upstream but maintainers have been unresponsive on most of our PRs which is pretty disappointing

  25. ArturAmpilogov commented on Apr 3, 2026

    @ArturAmpilogov

    Added a feature request to the Firebase team to gain more attention to this thread.
    This is an important and hot topic.

  26. niehaus1301 commented on Apr 4, 2026

    @niehaus1301

    Especially now with AI Coding tools monorepos are becoming more relevant

  27. 0x80 commented on Apr 9, 2026

    @0x80

    Hi everyone 👋 Sorry I haven’t been keeping the firebase-tools-with-isolate fork in sync as regularly as I promised. It is time for a structural solution…

    I have managed to automate the whole process via Github actions; A cron job will check daily for a new upstream version, sync it, re-apply the required changes, and publish a new version. So things should stay in sync from now on 👯

    I hope this also takes away some people’s fears around using the fork. It does not meaningfully change the behavior of firebase-tools, only how your files are organized before uploading.

    I have now also disabled "issues" on the fork repo, to avoid confusion, because any problems related to Isolate-package should be submitted on that repo instead.

    I have cleaned and up all of my other open-source projects lately, and there’s quite a few related to Firebase and GCP. You can find them here https://www.codecompose.com/open-source

    I recommend checking out gcp-job-runner. I find it super convenient for processing large amounts of documents, like doing a Firestore migration. It lets you define simple scripts and run them either locally or as a cloud run job, and as such it could be used for any CLI scripts that you wish to run.

    I’ve also bundled the family of typed-firestore packages together in an umbrella monorepo, and improved the documentation.

    Final thing maybe worth mentioning; Isolate-package should now also supports Bun lockfiles natively (untested), but that will be only useful if you use it to deploy to targets other than Firebase, like a Docker image straight to Cloud Run.

    Enjoy!

  28. 0x80 commented on Apr 11, 2026

    @0x80

    Version 15.14.0 now auto-detects a monorepo setup and uses that to opt-in to isolate-package.

    This means that it is now a drop-in replacement for firebase-tools, and you don't need to set isolate: true anymore in your Firebase config.

  29. kevmoo commented on Apr 16, 2026

    @kevmoo
    Contributor

    I just was able to do a mono-repo deploy!

  30. 0x80 commented on Apr 22, 2026

    @0x80

    The latest version of isolate-package now supports NPM lockfile pruning, meaning it preserves the actual locked versions, just like it already did for PNPM, Yarn v1 and Bun. It is currently included in the @next release of firebase-tools-with-isolate. Please give it a try if you use NPM with Firebase.

    I have also published an article about the different Firebase abstractions that I use. You can find it here https://codecompose.com/articles/my-favorite-firebase-abstractions/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions