next.js: Fail to deploy with firebase as a dependency

Comment from Maintainers

Firebase is now supported out of the box in Next.js 9.0.4 and newer!

Bug report

Describe the bug

This has been a journey, but I think I’ve pinned down the bug to something related to Firebase. I have a fairly simple app that I have attempted to deploy using now with the following configuration:

{
  "version": 2,
  "builds": [
    { 
      "src": "package.json", 
      "use": "@now/next" 
    }
  ]
}

While looking up the error, I found these two sources that suggest it might be a firebase issue: source 1 source 2

When I remove firebase as a dependency, everything deploys fine. Having said that, this app is entirely client-side for Firebase (not using firebase-admin) and the issues on spectrum seem to suggest that the issue is related to server configuration for Firebase… so the issue is not exactly the same.

I also came across this issue, which is also similar, but the person who posted it is attempting to deploy to firebase hosting, which I am not—I’m deploying with now.

To Reproduce

I created a minimal reproducible bug here:

https://github.com/samcorcos/next-firebase-bug

Follow the steps in the README to reproduce.

Expected behavior

I would expect the deploy to work with the firebase dependency.

System information

  • OS: macOS 10.14
  • Browser: Chrome 71.0.3578.98
  • Version of Next.js: ^7.0.2

Additional context

Here are the logs from the one of the failing deploys:

2019-01-17T00:17:01.292Z  Error: package.json does not exist at /package.json
                              at Object.PsoT.t.find (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:89:7243)
                              at Object.<anonymous> (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:223:35)
                              at Object.wPNL (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:223:708)
                              at n (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:1:225)
                              at Object.XpdW (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:145:22)
                              at n (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:1:225)
                              at Object.g1pB (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:162:22)
                              at n (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:1:225)
                              at Object.<anonymous> (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:89:114)
                              at Object.Ou8q (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:89:2606)
2019-01-17T00:17:01.325Z  (node:1) UnhandledPromiseRejectionWarning: Error: package.json does not exist at /package.json
                              at Object.PsoT.t.find (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:89:7243)
                              at Object.<anonymous> (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:223:35)
                              at Object.wPNL (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:223:708)
                              at n (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:1:225)
                              at Object.XpdW (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:145:22)
                              at n (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:1:225)
                              at Object.g1pB (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:162:22)
                              at n (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:1:225)
                              at Object.<anonymous> (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:89:114)
                              at Object.Ou8q (/var/task/.next/server/static/3W9EbRwr96wDUbrUY6qfc/pages/_app.js:89:2606)
2019-01-17T00:17:01.325Z  (node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
2019-01-17T00:17:01.325Z  (node:1) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I’m open to workarounds and inelegant solutions if you have any ideas. Thank you for your time 😄

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 4
  • Comments: 37 (6 by maintainers)

Most upvoted comments

First-Class Support

Firebase is now supported in Next.js 9.0.4 and newer out of the box! You can remove the below work around if you used it in your projects.

Previous Solution

Hello! Thank you everyone for your patience.

The root of the problem is that firebase is not designed to be used in a universal application. It’d be great to see this fixed from their side.

With that said, we’ve managed to come up with a work-around.

This solution is only applicable to users deploying on Now v2. If you are not deploying to Now v2, you need to do additional steps not defined here.

You can follow these steps to get up and running:

  1. Install @zeit/webpack-asset-relocator-loader@0.5.8 in your project.
  2. Be sure you’re using Next.js 8 (next@^8).
  3. Use the following plugin in your next.config.js:
    const withAssetRelocator = (nextConfig = {}) => {
      return Object.assign({}, nextConfig, {
        webpack(config, options) {
          const { isServer } = options
    
          if (isServer) {
            config.node = Object.assign({}, config.node, {
              __dirname: false,
              __filename: false,
            })
    
            config.module.rules.unshift({
              test: /\.(m?js|node)$/,
              parser: { amd: false },
              use: {
                loader: '@zeit/webpack-asset-relocator-loader',
                options: {
                  outputAssetBase: 'assets',
                  existingAssetNames: [],
                  wrapperCompatibility: true,
                  escapeNonAnalyzableRequires: true,
                },
              },
            })
          }
    
          if (typeof nextConfig.webpack === 'function') {
            return nextConfig.webpack(config, options)
          }
          return config
        },
      })
    }
    
  4. Be sure you are on the latest version of @now/next in your now.json.
    {
      "version": 2,
      "builds": [{ "src": "package.json", "use": "@now/next" }]
    }
    

@fakesamgregory looks like they changed some of the packaging in Firebase 6.0.0 which will require a different workaround. I saw the same error as you after upgrading.

The above fix worked for me up-to Firebase 5.11.1 so if you downgrade you should be good until a new method is found.

I’ve followed everything above and it’s worked great although when I visit my Next.js app in Now I’m getting a 502 Error. In my logs, I’m getting the below error…

module initialization error: Error     
     at Object.fs.openSync (fs.js:646:18)     
     at Object.fs.readFileSync (fs.js:551:33)     
     at fetch (/var/task/page.js:72816:34)
     at Root.load (/var/task/page.js:72850:13)
     at Root.loadSync (/var/task/page.js:72891:17)
     at Object.loadSync (/var/task/page.js:73092:17)
     at Object.pVxn (/var/task/page.js:72570:37)
     at __webpack_require__ (/var/task/page.js:23:31)
     at Object.lTqU (/var/task/page.js:48547:19)
     at __webpack_require__ (/var/task/page.js:23:31)
REPORT RequestId: 58410ea8-d30a-486d-b585-2890c1ae081e	
Duration: 47.64 ms  Billed Duration: 100 ms   Memory Size: 3008 MB  Max Memory Used: 109 MB	

I’ve done all of the steps above including removing dotenv and supplying my firebase keys directly to the initialisation to no avail. Does anyone have a link to a working example?

@brandontle Strangely enough, I can print process.env and see my keys, but I can’t access any of the values. Any idea why this might be?

Edit 3: This seems to work, for real this time. Add the following to your now.json:

{
"build": {
  "env": {
    // Your environment variables here...
  }
}
}

🚨Fix incoming.

Thanks to @Timer for being receptive to my complaining on Twitter and digging into the issue!

UPDATE

The fix has been included in the 0.5.3 release of webpack-asset-relocator-loader.
Please update your module and give it a shot!

This fixes any issues for me with running Firebase client side or server side.

If there are Firebase 6.0.0 issues in ncc, what would the replication be to check this? I’ve just tested upgrading our integration test to version 6 and it all seems to be working ok for me.

If you can share a minimal replication that would help a lot.

I’ve also created an issue specifically to track Firebase 6 support in https://github.com/zeit/ncc/issues/392.

Update for anyone else who runs into the same module initialization error when trying deploy a Firebase-enabled app to Now 2:

It appears that dotenv was the issue (with my setup). I had defined the Firebase config keys in a .env file, hoping to use dotenv to pass it to firebase.initializeApp(config). I have yet to figure out why, but this does not work.

As a temporary solution, I put my Firebase config keys directly into the config object as strings (instead of trying to read from process.env.FIREBASE_API_KEY, etc). If anyone has run into this and has a solution, do tell!

Nevertheless, with the instructions above from Timer, my app now deploys on Now 2! Thanks!

@nickbender Hey, thanks man! I had to degrade firebase to 5.7.1, react-with-firebase-auth to 1.0.0 and install grpc, request. It followed some more errors and then i had to remove next and install next@canary and now its working all fine on https://qiz.now.sh

@aedit I got things working by:

  1. Swapping from npm to yarn (yielded some warnings about side dependencies for several firebase packages)
  2. yarn add grpc. For whatever reason several pieces of the firebase codebase depend on the most recent grpc.
  3. Pinning a few slightly older working versions of both next and firebase

Relevant files here:

{
  "scripts": {
    "dev": "next",
    "build": "next build",
  },
  "dependencies": {
    "firebase": "^5.7.1",
    "grpc": "1.21.1",
    "next": "^7.0.2",
    "react": "^16.8.6",
    "react-audio-player": "^0.11.0",
    "react-dom": "^16.8.6",
    "react-hot-loader": "4.9.0",
    "request": "2.88.0"
  }
}

And my now.json

{
  "version": 2,
  "name": "piazza",
  "builds": [
    { "src": "/package.json", "use": "@now/next" },
    { "src": "/static/*", "use": "@now/static" }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/$1"
    }
  ]
}

and my entire next.config.js:

module.exports = {
  target: 'serverless'
}

It’s not an ideal fix, but I was able to make this work for serverless firebase functions by specifically excluding “grpc” via webpack:

 webpack(config, options) {
    if (process.env.NODE_ENV !== "development") {
      config.externals = {
        grpc: "grpc"
      };
    }
    return config;
  }

Both firestore and firebase auth still work (in the browser, obviously) for production, for some reason it causes hook errors when running it through the next command. Not sure what you’d have to do to run into something that actually uses GRPC 😬 .

I’ve created an issue to track implementing a solution for this on ncc: https://github.com/zeit/ncc/issues/240

Thanks for the tip! I’ve just tried both of those things, and I now get this error. Progress… I think?

@noahtallen You might want to try the next@canary version. You’ll need to npm i --save next@canary and update your now.json to use "use": "@now/next@canary"