Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fail to deploy with firebase as a dependency #6073

Closed
samcorcos opened this issue Jan 17, 2019 · 37 comments
Closed

Fail to deploy with firebase as a dependency #6073

samcorcos opened this issue Jan 17, 2019 · 37 comments

Comments

@samcorcos
Copy link

samcorcos commented Jan 17, 2019

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 😄

@noahtallen
Copy link

I'm getting an identical error. I actually found this repo trying to fix it. Unfortunately, his solution is to import from the firebase submodules rather than directly from firebase, but I already do that (note, I'm using Typescript):

import * as firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
import 'firebase/storage'

const prodConfig = {
  apiKey: 'x',
  authDomain: 'x',
  databaseURL: 'x',
  projectId: 'x',
  storageBucket: 'x',
  messagingSenderId: 'x',
}

const config = prodConfig
if (!firebase.apps.length) {
  firebase.initializeApp(config)
}

const firestore = firebase.firestore()
const settings = { timestampsInSnapshots: true }
firestore.settings(settings)
const auth = firebase.auth
const storage = firebase.storage()

export {
  firestore,
  auth,
  storage,
}

And then it logs this every time you try to load the site:

01/18 03:47 PM (6m)
Error: package.json does not exist at /package.json
    at Object.PsoT.t.find (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:89:7612)
    at Object.<anonymous> (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:215:35)
    at Object.wPNL (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:215:708)
    at n (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:1:225)
    at Object.XpdW (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:145:10)
    at n (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:1:225)
    at Object.g1pB (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:162:10)
    at n (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:1:225)
    at Object.<anonymous> (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:89:90)
    at Object.Ou8q (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:89:2618)
01/18 03:47 PM (6m)
(node:1) UnhandledPromiseRejectionWarning: Error: package.json does not exist at /package.json
    at Object.PsoT.t.find (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:89:7612)
    at Object.<anonymous> (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:215:35)
    at Object.wPNL (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:215:708)
    at n (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:1:225)
    at Object.XpdW (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:145:10)
    at n (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:1:225)
    at Object.g1pB (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:162:10)
    at n (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:1:225)
    at Object.<anonymous> (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:89:90)
    at Object.Ou8q (/var/task/.next/server/static/_ietpRSOt3ON68R3oNi1R/pages/_app.js:89:2618)
01/18 03:47 PM (6m)
(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)
01/18 03:47 PM (6m)
(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.

@samcorcos
Copy link
Author

@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"

@noahtallen
Copy link

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

@timneutkens
Copy link
Member

I've created an issue to track implementing a solution for this on ncc: vercel/ncc#240

@samcorcos
Copy link
Author

samcorcos commented Jan 29, 2019

@noahtallen If you need to get something up and running, I was able to get it to compile to static HTML just fine: next build && next export. I should note that this is using next: 7.0.2, not using next@canary.

Then I deployed it to Firebase's CDN and it's functional. It won't give you server-side rendering, but it isn't broken 😆

@noahtallen
Copy link

noahtallen commented Jan 29, 2019

For some reason, I'm now getting 404s for every single page when I build locally (on latest canary), but no errors thrown in the console. Additionally, when I export using those commands, it doesn't appear to build any page other than app & error. Not that this is the same issue, of course :P

@Timer
Copy link
Member

Timer commented Feb 26, 2019

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" }]
    }

@Timer Timer closed this as completed Feb 26, 2019
@didymu5
Copy link

didymu5 commented Mar 29, 2019

What would be a another recommended 'hosted' store option similar to Firebase?

@bfulop
Copy link

bfulop commented Mar 30, 2019

I had a similar issue, ie Firestore not working in Zeit, but the Firebase Realtime Database does work!

@brandontle
Copy link

brandontle commented Apr 4, 2019

@Timer Hey there, thanks for the tips. I tried to follow your steps, but ran into another error TypeError: Cannot read property 'readableIdentifier' of null.

Would you mind taking a look? Or do you have any other suggestions on how to deploy a Next+Firebase/Firestore app (either with Now, Firebase hosting, etc.)?

I'm running Next@8.0.5-canary.8 and have @zeit/webpack-asset-relocator-loader installed.

Local development logs:

Starting the development server ...
  > Waiting on http://localhost:3000
> Using external babel configuration> Location: "/Users/brandon/nextProject/babel.config.js"
(node:23679) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'readableIdentifier' of null
    at Object.ModuleFilenameHelpers.createFilename (/Users/brandon/nextProject/
node_modules/webpack/lib/ModuleFilenameHelpers.js:83:28)    at files.forEach (/Users/brandon/nextProject/node_modules/webpack/lib/Sourc
eMapDevToolPlugin.js:149:33)    at Array.forEach (<anonymous>)
    at compilation.hooks.afterOptimizeChunkAssets.tap (/Users/ble-mbp-16/Projects/rowsAndColum
ns/node_modules/webpack/lib/SourceMapDevToolPlugin.js:130:12)
    at SyncHook.eval [as call] (eval at create (/Users/brandon/nextProject/node
_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:7:1)
    at SyncHook.lazyCompileHook (/Users/brandon/nextProject/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.optimizeChunkAssets.callAsync.err (/Users/brandon/nextProject/node_modules/webpack/lib/Compilation.js:1315:42)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/brandon/nextProject/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/brandon/nextProject/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.additionalAssets.callAsync.err (/Users/brandon/nextProject/node_modules/webpack/lib/Compilation.js:1311:36)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/brandon/nextProject/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/brandon/nextProject/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.optimizeTree.callAsync.err (/Users/brandon/nextProject/node_modules/webpack/lib/Compilation.js:1307:32)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/brandon/nextProject/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/brandon/nextProject/node_modules/tapable/lib/Hook.js:154:20)
    at Compilation.seal (/Users/brandon/nextProject/node_modules/webpack/lib/Compilation.js:1244:27)
(node:23679) 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: 1)
(node:23679) [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.

(Attempted) Now production deployment logs:

2019-04-04T02:34:45.931Z  warning No license field
2019-04-04T02:34:45.934Z  [1/4] Resolving packages...
2019-04-04T02:34:46.423Z  [2/4] Fetching packages...
2019-04-04T02:34:46.951Z  [3/4] Linking dependencies...
2019-04-04T02:34:47.099Z  [4/4] Building fresh packages...
2019-04-04T02:34:47.109Z  success Saved lockfile.
2019-04-04T02:34:47.112Z  warning No license field
2019-04-04T02:34:47.119Z  success Saved 25 new dependencies.
2019-04-04T02:34:47.119Z  info Direct dependencies
2019-04-04T02:34:47.120Z  └─ @now/next@0.1.3-canary.5
2019-04-04T02:34:47.121Z  info All dependencies
2019-04-04T02:34:47.121Z  ├─ @now/next@0.1.3-canary.5
                          ├─ @now/node-bridge@1.0.1
                          ├─ cross-spawn@6.0.5
2019-04-04T02:34:47.121Z  ├─ end-of-stream@1.4.1
                          ├─ execa@1.0.0
                          ├─ fs-extra@7.0.1
                          ├─ get-stream@4.1.0
                          ├─ graceful-fs@4.1.15
                          ├─ is-stream@1.1.0
                          ├─ isexe@2.0.0
                          ├─ jsonfile@4.0.0
                          ├─ nice-try@1.0.5
                          ├─ npm-run-path@2.0.2
                          ├─ once@1.4.0
2019-04-04T02:34:47.122Z  ├─ p-finally@1.0.0
                          ├─ path-key@2.0.1
                          ├─ pump@3.0.0
                          ├─ semver@5.7.0
                          ├─ shebang-command@1.2.0
                          ├─ shebang-regex@1.0.0
                          ├─ signal-exit@3.0.2
                          ├─ strip-eof@1.0.0
                          ├─ universalify@0.1.2
                          ├─ which@1.3.1
                          └─ wrappy@1.0.2
2019-04-04T02:34:47.123Z  Done in 1.27s.
2019-04-04T02:35:01.359Z  running builder.exports.build...
2019-04-04T02:35:01.361Z  downloading user files...
2019-04-04T02:35:02.134Z  MODE: serverless
2019-04-04T02:35:02.134Z  installing dependencies...
                          installing to /tmp/5055f019
2019-04-04T02:35:02.389Z  yarn install v1.13.0
2019-04-04T02:35:02.634Z  [1/4] Resolving packages...
2019-04-04T02:35:03.765Z  [2/4] Fetching packages...
2019-04-04T02:35:31.146Z  info fsevents@1.2.4: The platform "linux" is incompatible with this module.
2019-04-04T02:35:31.146Z  info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
2019-04-04T02:35:31.169Z  [3/4] Linking dependencies...
2019-04-04T02:35:31.178Z  warning "@brandontle/rich-markdown-editor > @tommoor/slate-edit-list@0.19.0-0" has incorrect peer dependency "slate@^0.40.0".
2019-04-04T02:35:31.179Z  warning "@brandontle/rich-markdown-editor > eslint-plugin-flowtype@2.50.3" has unmet peer dependency "eslint@>=2.0.0".
2019-04-04T02:35:31.179Z  warning "@brandontle/rich-markdown-editor > eslint-plugin-prettier@2.7.0" has unmet peer dependency "prettier@>= 0.11.0".
2019-04-04T02:35:31.181Z  warning "@brandontle/rich-markdown-editor > react-medium-image-zoom@3.0.15" has unmet peer dependency "prop-types@^15.5.8".
2019-04-04T02:35:31.182Z  warning "@brandontle/rich-markdown-editor > slate-md-serializer@5.2.3" has incorrect peer dependency "slate@~0.34.0".
2019-04-04T02:35:31.186Z  warning " > @microlink/react@3.0.5" has unmet peer dependency "styled-components@4".
2019-04-04T02:35:31.187Z  warning "firebase > @firebase/database@0.3.16" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.187Z  warning "firebase > @firebase/firestore@1.1.1" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.188Z  warning "firebase > @firebase/functions@0.4.3" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.188Z  warning "firebase > @firebase/messaging@0.3.15" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.188Z  warning "firebase > @firebase/storage@0.2.12" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.189Z  warning "firebase > @firebase/auth > @firebase/auth-types@0.5.5" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.189Z  warning "firebase > @firebase/auth > @firebase/auth-types@0.5.5" has unmet peer dependency "@firebase/util@0.x".
                          warning "firebase > @firebase/database > @firebase/database-types@0.3.8" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.189Z  warning "firebase > @firebase/firestore > @firebase/firestore-types@1.1.1" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.190Z  warning "firebase > @firebase/functions > @firebase/messaging-types@0.2.8" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.190Z  warning "firebase > @firebase/storage > @firebase/storage-types@0.2.8" has unmet peer dependency "@firebase/app-types@0.x".
2019-04-04T02:35:31.190Z  warning "firebase > @firebase/storage > @firebase/storage-types@0.2.8" has unmet peer dependency "@firebase/util@0.x".
2019-04-04T02:35:31.197Z  warning "@emotion/babel-preset-css-prop > @babel/plugin-transform-react-jsx > @babel/plugin-syntax-jsx@7.2.0" has unmet peer dependency "@babel/core@^7.0.0-0".
2019-04-04T02:35:31.201Z  warning " > react-feather@1.1.6" has unmet peer dependency "prop-types@>= 15".
2019-04-04T02:35:31.202Z  warning " > react-ga@2.5.6" has unmet peer dependency "prop-types@^15.6.0".
2019-04-04T02:35:31.203Z  warning " > react-sortable-hoc@1.8.3" has unmet peer dependency "prop-types@^15.5.7".
2019-04-04T02:35:31.205Z  warning " > @emotion/babel-preset-css-prop@10.0.9" has unmet peer dependency "@babel/core@^7.0.0".
2019-04-04T02:35:31.206Z  warning "@emotion/babel-preset-css-prop > @babel/plugin-transform-react-jsx@7.3.0" has unmet peer dependency "@babel/core@^7.0.0-0".
                          warning "@emotion/babel-preset-css-prop > @emotion/babel-plugin-jsx-pragmatic@0.1.2" has unmet peer dependency "@babel/core@^7.0.0".
2019-04-04T02:35:31.206Z  warning "@zeit/next-typescript > @babel/preset-typescript@7.1.0" has unmet peer dependency "@babel/core@^7.0.0-0".
                          warning "@zeit/next-typescript > @babel/preset-typescript > @babel/plugin-transform-typescript@7.2.0" has unmet peer dependency "@babel/core@^7.0.0-0".
                          warning "@zeit/next-typescript > @babel/preset-typescript > @babel/plugin-transform-typescript > @babel/plugin-syntax-typescript@7.2.0" has unmet peer dependency "@babel/core@^7.0.0-0".
2019-04-04T02:35:31.206Z  warning " > babel-loader@8.0.4" has unmet peer dependency "@babel/core@^7.0.0".
                          warning " > babel-loader@8.0.4" has unmet peer dependency "webpack@>=2".
2019-04-04T02:35:45.657Z  [4/4] Building fresh packages...
2019-04-04T02:35:46.885Z  Done in 44.50s.
2019-04-04T02:35:46.899Z  running user script...
2019-04-04T02:35:46.900Z  running "yarn run now-build"
2019-04-04T02:35:47.144Z  yarn run v1.13.0
2019-04-04T02:35:47.225Z  $ next build
2019-04-04T02:35:48.072Z  Creating an optimized production build ...
2019-04-04T02:35:48.073Z  
2019-04-04T02:35:49.118Z  > Using external babel configuration
2019-04-04T02:35:49.118Z  > Location: "/tmp/5055f019/babel.config.js"
2019-04-04T02:39:18.252Z  Compiled with warnings.
2019-04-04T02:39:18.252Z  ./node_modules/next-server/dist/server/require.js
                          Critical dependency: the request of a dependency is an expression
                          
                          ./node_modules/next-server/dist/server/require.js
                          Critical dependency: the request of a dependency is an expression
                          
                          ./node_modules/encoding/lib/iconv-loader.js
                          Critical dependency: the request of a dependency is an expression
                          
                          ./node_modules/grpc/src/grpc_extension.js
                          Critical dependency: the request of a dependency is an expression
                          
                          ./node_modules/grpc/node_modules/node-pre-gyp/lib/pre-binding.js
                          Critical dependency: the request of a dependency is an expression
                          
                          ./node_modules/grpc/node_modules/node-pre-gyp/lib/util/versioning.js
                          Critical dependency: the request of a dependency is an expression
                          
                          ./node_modules/bytebuffer/dist/bytebuffer-node.js
                          Module not found: Can't resolve 'memcpy' in '/tmp/5055f019/node_modules/bytebuffer/dist'
2019-04-04T02:39:18.310Z  Done in 211.17s.
2019-04-04T02:39:18.315Z  preparing lambda files...
2019-04-04T02:39:36.623Z  running builder.exports.prepareCache...
2019-04-04T02:39:36.624Z  preparing cache ...
2019-04-04T02:39:36.628Z  clearing old cache ...
2019-04-04T02:39:38.213Z  module initialization error: Error
                              at Object.PsoT.exports.find (/var/task/page.js:1807:22704)
                              at Object.<anonymous> (/var/task/page.js:2049:101)
                              at Object.wPNL (/var/task/page.js:2049:1066)
                              at __webpack_require__ (/var/task/page.js:1:339)
                              at Object.XpdW (/var/task/page.js:1896:13)
                              at __webpack_require__ (/var/task/page.js:1:339)
                              at Object.g1pB (/var/task/page.js:1966:28)
                              at __webpack_require__ (/var/task/page.js:1:339)
                              at Object.<anonymous> (/var/task/page.js:1807:196)
                              at Object.Ou8q (/var/task/page.js:1807:4516)
2019-04-04T02:39:38.255Z  REPORT RequestId: efa1e27f-1f01-415f-acb7-2de455195866        Duration: 49.61 ms    Billed Duration: 100 ms         Memory Size: 3008 MB    Max Memory Used: 110 MB
2019-04-04T02:39:38.255Z  module initialization error
                          Error
2019-04-04T02:39:39.351Z  copying build files for cache ...
2019-04-04T02:39:39.351Z  producing cache file manifest ...
2019-04-04T02:39:39.402Z  module initialization error: Error
                              at Object.PsoT.exports.find (/var/task/page.js:1807:22704)
                              at Object.<anonymous> (/var/task/page.js:2049:101)
                              at Object.wPNL (/var/task/page.js:2049:1066)
                              at __webpack_require__ (/var/task/page.js:1:339)
                              at Object.XpdW (/var/task/page.js:1896:13)
                              at __webpack_require__ (/var/task/page.js:1:339)
                              at Object.g1pB (/var/task/page.js:1966:28)
                              at __webpack_require__ (/var/task/page.js:1:339)
                              at Object.<anonymous> (/var/task/page.js:1807:196)
                              at Object.Ou8q (/var/task/page.js:1807:4516)
2019-04-04T02:39:39.439Z  REPORT RequestId: 806b5b14-55b6-4494-b9ba-d1e7868980fe        Duration: 44.75 ms    Billed Duration: 100 ms         Memory Size: 3008 MB    Max Memory Used: 75 MB
2019-04-04T02:39:39.439Z  module initialization error
                          Error

next.config.js:

const webpack = require('webpack');
require('dotenv').config();
const withTypescript = require('@zeit/next-typescript');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

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;
    },
  });
};

module.exports = withAssetRelocator(
  withTypescript({
    target: 'serverless',
    webpack(config) {
      if (process.env.ANALYZE) {
        config.plugins.push(
          new BundleAnalyzerPlugin({
            analyzerMode: 'server',
            analyzerPort: 8888,
            openAnalyzer: true,
          })
        );
      }
      // to enable reading variables from .env file
      const env = Object.keys(process.env).reduce((acc, curr) => {
        acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
        return acc;
      }, {});

      config.plugins.push(new webpack.DefinePlugin(env));
      return config;
    },
    cssModules: true,
  })
);

babel.config.js:

module.exports = (api) => {
  api.cache(true)
  return {
    presets: [
      'next/babel',
      '@zeit/next-typescript/babel',
      '@emotion/babel-preset-css-prop'
    ],
    plugins: [
      'emotion',
      '@babel/proposal-class-properties',
      '@babel/proposal-object-rest-spread',
      ['transform-define', {
        'process.env.NODE_ENV': process.env.NODE_ENV
      }]
    ]
  }
}

now.json:

{
  "version": 2,
  "name": "nextProject",
  "builds": [{ "src": "next.config.js", "use": "@now/next@canary" }],
  "routes": [
    { "src": "/edit/(?<postId>[^/]+)$", "dest": "/edit?postId=$postId" },
    {
      "src": "/_next/static/(?:[^/]+/pages|chunks|runtime)/.+",
      "headers": { "cache-control": "immutable" }
    }
  ]
}

@brandontle
Copy link

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!

@samcorcos
Copy link
Author

@brandontle Your issue might be related to this:

vercel/webpack-asset-relocator-loader#3

Try using a different version number—perhaps 1.x for the webpack asset relocator.

@guybedford
Copy link
Contributor

@brandontle thanks for the update here. Could you share the code example of how you were loading the .env file and passing it to firebase.initializeApp? The asset relocator should be able to handle these cases.

@dcrck
Copy link

dcrck commented Apr 13, 2019

@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...
  }
}
}

@JoshRozin
Copy link

JoshRozin commented Apr 17, 2019

Still an issue for me. Been fighting this for a week now...

From what I've seen, it seems to be an issue with webpack or gRPC. Everytime I remove gRPC dependent modules, it is a okay.

@yareyaredesuyo
Copy link

yareyaredesuyo commented Apr 23, 2019

for me, both using next@canary and withAssetRelocator worked.

#6073 (comment)
#6073 (comment)

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
    },
  })
}

module.exports = withAssetRelocator(withCSS(withTypescript(withSass({
  target: "serverless"
}))));

now.json

{
  "version": 2,
  "name": "nextjs",
  "builds": [
      { "src": "package.json",
        "use": "@now/next@canary",
        "config": {
          "maxLambdaSize": "10mb"
        }
      }
  ]
}

@brandontle
Copy link

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

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

Nice, wow, this is the answer. Works perfectly, thanks @rederekt.

Oddly enough, using this method, I still need to load and read a .env file in my next.config.js file. The .env file can be empty, but if I remove it, the environment variables specified in now.json never make it to process.env (so Firebase fails to initialize). Maybe a residual from all of my previous attempts to fix dotenv.

@0x5am5
Copy link

0x5am5 commented May 12, 2019

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?

@geemanjs
Copy link

@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.

@0x5am5
Copy link

0x5am5 commented May 14, 2019

@Geeman201 This worked. Thank you! Firebase is at 5.1.11

Something not mentioned above that set me back was that env variables (process.env) are only available in getInitialProps method when using serverless. I would then need to pass them as props to the component.

Thank you for everyones hard work. It's helped me a lot.

@guybedford
Copy link
Contributor

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 vercel/ncc#392.

@AlexGilleran

This comment has been minimized.

@aedit
Copy link

aedit commented Jun 5, 2019

I had a similar issue, ie Firestore not working in Zeit, but the Firebase Realtime Database does work!

@bfulop How? I can't use Realtime Database either

@nickbender

This comment has been minimized.

@bradgarropy
Copy link

bradgarropy commented Jun 6, 2019

@nickbender Did you even use the withAssetRelocator?

@nickbender
Copy link

nickbender commented Jun 6, 2019

@bradgarropy Nope, but that may be required for next 8/ and firebase 6.

@aedit
Copy link

aedit commented Jun 6, 2019

@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

@embpdaniel
Copy link

embpdaniel commented Jun 10, 2019

I'm deploying to firebase cloud functions with:

  • 8.1.1-canary.44
  • 'serverless' as target
  • assets relocator plugin set up as mentioned previously in this issue
  • importing firebase into my project as submodules

Following these steps did help the problem (I can at least build the app successfully now), but if I deploy my app to my firebase function I get this error.

Error: The gRPC binary module was not installed. This may be fixed by running "npm rebuild"
Original error: Cannot find module './assets/src/node/extension_binary/node-v64-darwin-x64-unknown/grpc_node.node'
    at Object.1LCg (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:5515:17)
    at __webpack_require__ (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:23:31)
    at Object.IRvU (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:41213:12)
    at __webpack_require__ (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:23:31)
    at Object.T08b (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:57907:27)
    at __webpack_require__ (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:23:31)
    at Object.YLfK (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:64831:14)
    at __webpack_require__ (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:23:31)
    at Object.dqYV (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:78165:12)
    at __webpack_require__ (/Users/naneco/EMBP/Clients/bids/bids-react/dist/functions/next/serverless/pages/index.js:23:31)
⚠  Your function was killed because it raised an unhandled error.

I tried running npm rebuild but no luck. I also added grpc as a dependency. Also did not work.

I tried older versions of firebase (5.7.1) (5.11.1) and no luck either.

If I disable my firebase imports in my project and deploy. It deploys just fine, so it's definitely an issue with importing firebase into my project.

I'm out of ideas. If anyone can help I would be very grateful 🤗

@bradgarropy
Copy link

bradgarropy commented Jun 10, 2019

@embpdaniel Something that helped me out a lot was switching to yarn.

@embpdaniel
Copy link

Thanks for the tip @bradgarropy . I just tried it, but I get the same error :/

@bradgarropy
Copy link

bradgarropy commented Jun 11, 2019

🚨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.

@bradgarropy
Copy link

To summarize, the fix to webpack-asset-relocator-loader solves the 502 error.
@Timer's comment remains the only way to bootstrap Firebase with Next.js/Now.

Looking forward to a future release of Next.js that integrates the webpack-asset-relocator-loader code directly!

@skaptox
Copy link

skaptox commented Jun 24, 2019

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 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" }]
    }

That works, but after I used it my bundle sizes increased from

├── λ product/ProductAvatarUser (364.83KB) [sfo1]
├── λ _error (362.52KB) [sfo1]
├── λ product/ProductContact (363.08KB) [sfo1]
├── λ product/ProductSocialShare (363.01KB) [sfo1]
├── λ product/ProductInfo (413.21KB) [sfo1]

to

├── λ _error (10.29MB) [sfo1]
├── λ auth (10.5MB) [sfo1]
├── λ index (10.42MB) [sfo1]
├── λ product (10.41MB) [sfo1]
├── λ product/ProductAvatarUser (10.3MB) [sfo1]
└── 21 output items hidden

Is that normal?

@Timer
Copy link
Member

Timer commented Jun 25, 2019

Yes @skaptox -- Firebase requires huge server side dependencies.

@embpdaniel
Copy link

@skaptox I have a separate NextJS application that utilizes Firebase 6.1.0, which I deploy to an Elastic Beanstalk environment.

I don't utilize the firebase library on the server (I block any initialization attempts), but at least it can exist on the app without throwing errors. In other words the import statements in the app don't make the build flip out.

You mentioned the root of the problem is Firebase not being designed to be a universal application. I'm curious why it works in this case, and not when I deploy to Firebase. Is it because I set the target to serverless on Firebase, and that's why it becomes incompatible? 🤔

@Pushplaybang

This comment has been minimized.

@Timer
Copy link
Member

Timer commented Jul 23, 2019

I'm locking this issue because it is solved by #6073 (comment). Please follow these instructions until Next.js 9.2 (we estimate) for a proper fix.

The above solution works with Next.js 8 and 9.

Be very careful to use this exact version: @zeit/webpack-asset-relocator-loader@0.5.8

@vercel vercel locked as resolved and limited conversation to collaborators Jul 23, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests