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

Cannot find module 'firebase-admin/app' #1488

Open
sankalpsans opened this issue Nov 7, 2021 · 39 comments
Open

Cannot find module 'firebase-admin/app' #1488

sankalpsans opened this issue Nov 7, 2021 · 39 comments

Comments

@sankalpsans
Copy link

package.json requirements look like this –

  "dependencies": {
    "@sentry/node": "^5.30.0",
    "body-parser": "1.19.0",
    "express": "^4.17.1",
    "firebase-admin": "10.0.0",
    "mysql": "^2.18.1",
    "pug": "3.0.2"
  }

node_modules has the corresponding module in the path ~/node_modules/firebase-admin/lib/app

Node code reads as –

const initializeApp  = require('firebase-admin/app');

And when the app is run, the following stacktrace emerges.

 Error: Cannot find module 'firebase-admin/app'
     at Function.Module._resolveFilename (module.js:547:15)
     at Function.Module._load (module.js:474:25)
     at Module.require (module.js:596:17)
     at require (internal/module.js:11:18)
     at Object.<anonymous> (/var/www/html/project/backend/main.js:16:24)
     at Module._compile (module.js:652:30)
     at Object.Module._extensions..js (module.js:663:10)
     at Module.load (module.js:565:32)
     at tryModuleLoad (module.js:505:12)
     at Function.Module._load (module.js:497:3)
@google-oss-bot
Copy link

I found a few problems with this issue:

  • I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.
  • This issue does not seem to follow the issue template. Make sure you provide all the required information.

@shalomhalbert
Copy link

shalomhalbert commented Nov 7, 2021

I have the same issue. For some reason, running npm install resolved the error when running mocha tests from a non-debug terminal instance in Visual Studio Code, but running mocha tests from a debug terminal instance still yields this error. The node_modules package is definitely installed.

@shalomhalbert
Copy link

shalomhalbert commented Nov 7, 2021

Solved it by ignoring the import recommendation. Instead of

'use strict';

const { initializeApp } = require('firebase-admin/app');
const { getFirestore, Timestamp, GeoPoint } = require('firebase-admin/firestore');

exports.initializeApp = () => initializeApp();
exports.getFirestore = () => getFirestore();
exports.Timestamp = Timestamp;
exports.GeoPoint = GeoPoint;

I am now using what existed before v10:

'use strict';

const firebaseAdmin = require('firebase-admin');

exports.initializeApp = () => firebaseAdmin.initializeApp();
exports.getFirestore = () => firebaseAdmin.firestore();
exports.Timestamp = firebaseAdmin.firestore.Timestamp;
exports.GeoPoint = firebaseAdmin.firestore.GeoPoint;

@hiranya911
Copy link
Contributor

Code given above worked fine when executed through Node.js 12. Here's the output of the execution with an added console.log statement:

% cat main.js 
'use strict';

const { initializeApp } = require('firebase-admin/app');
const { getFirestore, Timestamp, GeoPoint } = require('firebase-admin/firestore');

exports.initializeApp = () => initializeApp();
exports.getFirestore = () => getFirestore();
exports.Timestamp = Timestamp;
exports.GeoPoint = GeoPoint;

console.log(exports);


% node main.js 
{
  initializeApp: [Function],
  getFirestore: [Function],
  Timestamp: [class Timestamp],
  GeoPoint: [class GeoPoint]
}

Also I can do the following on a Node.js REPL:

% node
Welcome to Node.js v12.22.0.
Type ".help" for more information.
> const { initializeApp } = require('firebase-admin/app')
undefined
> initializeApp
[Function: initializeApp]

May be somebody can share a minimal and complete repro of the issue? Something that we can download and run to repro the problem?

@sankalpsans
Copy link
Author

sankalpsans commented Nov 9, 2021

@hiranya911 I am currently using node v17.0.1. Is it known to not work with this? Is the solution to downgrade to v12 instead?

Edit – I can confirm that downgrading to v12 did solve the issue.

@sankalpsans
Copy link
Author

@shalbert94 Importing the top level module and then accessing internal things like you suggested works.
That is exactly the workaround that I proceeded with.

So, either the docs need updating, or the library itself does.

@hiranya911
Copy link
Contributor

Works fine on Node 17 too:

$ node
Welcome to Node.js v17.0.1.
Type ".help" for more information.
> const { initializeApp }  = require('firebase-admin/app')
undefined
> initializeApp
[Function: initializeApp]

This is most likely a problem specific to your environment/implementation. We will need a complete, minimal repro to know for sure.

As fas as our library is concerned, we correctly declare the new module entry points in our package.json file:

"exports": {
".": "./lib/index.js",
"./app": {
"require": "./lib/app/index.js",
"import": "./lib/esm/app/index.js"
},

All Node.js versions 12 and up, should support it.

@hiranya911
Copy link
Contributor

hiranya911 commented Nov 9, 2021

Edit – I can confirm that downgrading to v12 did solve the issue.

Assuming there are no other libraries, frameworks or custom module loaders in play, more likely explanation is your Node 17 setup was somehow loading an old version of firebase-admin (e.g. v9), that didn't have the new module exports. Changing to Node 12 pulled in the latest version of the library, and picked up the new entry points. Just a guess.

@hiranya911
Copy link
Contributor

I pushed a copy of my attempt to repro this issue to https://github.com/firebase/firebase-admin-node/tree/hkj-repro-1488/nodetest. Feel free to play with it and see if you can still repro the problem.

@Bandit
Copy link

Bandit commented Nov 9, 2021

I'm also getting this error when using the snippet provided:

import { initializeApp, applicationDefault } from 'firebase-admin/app';

=> Error: Cannot find module 'firebase-admin/app'

Node v14.16.1

Confirming that using import firebaseAdmin from 'firebase-admin' resolves it, however that's a big headache. For now I've given up on this approach and gone back to using import Firestore from '@google-cloud/firestore' (and it looks like firebase-admin just wraps that anyway so no harm I guess?)

@hiranya911
Copy link
Contributor

@Bandit can you share a complete repro with us? Something similar to the complete example I've shared above in my last comment.

@hiranya911
Copy link
Contributor

hiranya911 commented Nov 9, 2021

Folks who are seeing this error also please check their library version using one of the following methods:

Using npm ls

$ npm ls firebase-admin       
mods@1.0.0 
└── firebase-admin@10.0.0

Directly checking the package.json of the library

$ grep "version" node_modules/firebase-admin/package.json
  "version": "10.0.0"

If the version is indeed 10.x or higher, please share a complete repro that we can run.

@Bandit
Copy link

Bandit commented Nov 9, 2021

Confirmed I'm using firebase-admin@10.0.0

I'll see about building a repro when I get some time, but I'm assuming it's related to Vite (using Vite + Sveltekit). Perhaps fixed by this hot-off-the-press PR vitejs/vite#5593? Or maybe it's this bug vitejs/vite#4340? Bit beyond my pay grade

@hiranya911
Copy link
Contributor

We encountered the issue in Vite during alpha testing. See #1340 (also vitejs/vite#3953). It's a bug in their module resolver. We cannot do much about that on our end, but it sounds like the PR you've linked above is expected to fix it.

Other platforms with known issues include Jest and ESLint (see #1481)

@BigBallard
Copy link

Can confirm this is an issue when creating a graphql express application. Version is 10.0.0

import { initializeApp } from "firebase-admin/app"
import { getAuth } from "firebase-admin/lib/auth"

const firebaseApp = initializeApp()
const auth = getAuth(firebaseApp)
> nodemon ./src/index.ts

[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src\**\*.ts
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node ./src/index.ts`
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/auth' is not defined by "exports" in E:\TrailTrek\trail-trek-back\node_modules\firebase-admin\package.json
    at new NodeError (node:internal/errors:363:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:335:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:560:3)
    at resolveExports (node:internal/modules/cjs/loader:476:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:516:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:913:27)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (C:\ProgramData\nvm\v16.4.0\node_modules\ts-node\node_modules\@cspotcode\source-map-support\source-map-support.js:679:30)
    at Function.Module._load (node:internal/modules/cjs/loader:772:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:93:18) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'

@hiranya911
Copy link
Contributor

@DallasP9124 your import is wrong:

import { getAuth } from "firebase-admin/lib/auth"

Should be corrected as:

import { getAuth } from "firebase-admin/auth"

@adgang
Copy link

adgang commented Nov 17, 2021

Can confirm this issue occurs, as of today, on

node --version
v14.18.0

Repro is just following the firebase setup docs, albeit with typescript imports.
https://firebase.google.com/docs/admin/setup

Update: Visual Studio code is able to see the firebase-admin/app module though. Its just that when I run a test case with jest with minimal setup of FCM admin, the error occurs.

Looks like my issue is more related to:
#1481

For now, the workaround is good.

@BigBallard
Copy link

@hiranya911 that did fix it. I was using WebStorm and it resolved the import to the wrong location.

@davidpirates
Copy link

I got fixed by updating fireabse-admin and node version as below.
firebase-admin: 10.0.0
node: v14.15.4

@itssumitrai
Copy link

any updates on this issue ? I am not able to use modular imports on Node 16
Cannot find module 'firebase-admin/auth'
My installed version is 10.0.0

@TheSecurityDev
Copy link

I started getting this after installing the eslint-plugin-node module and enabling the plugin. The rule node/no-missing-import was causing the error. I fixed it by adding allowModules: ["firebase-admin"] in the rule config, like this:

"node/no-missing-import": [
  "error",
    {
      allowModules: ["firebase-admin"],
    },
  ],

@hiranya911
Copy link
Contributor

hiranya911 commented Dec 12, 2021

@TheSecurityDev Yes, ESLint is another known case. See my earlier comment #1488 (comment)

Open bug report in ESLint project: import-js/eslint-plugin-import#1868

@pooyasa
Copy link

pooyasa commented Dec 15, 2021

Same problem here. The suggested method in the documentation did not work.

However this solved it:

import * as admin from 'firebase-admin';

admin.initializeApp();

const db = admin.firestore();
const bucket = admin.storage().bucket();
const auth = admin.auth();

@reslear
Copy link

reslear commented Dec 16, 2021

same problem

node: v16.13.0

"typescript": "^4.5.4"
"firebase-admin": "^10.0.1",
"ts-node": "^10.4.0",
"ts-node-dev": "2.0.0-0",

eslint

{
    'import/no-unresolved': [
      'error',
      {
        ignore: ['^firebase-admin/.+'],
      },
    ],
    'node/no-missing-import': [
      'error',
      {
        allowModules: ['firebase-admin'],
      },
    ],
}

working only importing type

import type { MulticastMessage } from 'firebase-admin/messaging'

thx @pooyasa I also had to go back

@Benjamin-Dobell
Copy link

A co-worker had a similar issue, so just chiming in in case it helps someone. Basically, make sure you're running tooling that supports package.json exports field.

firebase-admin/app isn't a real file on disk, it's mapped as per:

"./app": {
"require": "./lib/app/index.js",
"import": "./lib/esm/app/index.js"
},

In our case we were seeing discrepancies between developers' machines. Ensuring everyone was running Node 12.7 or greater resolved the issue.

@codingedgar
Copy link

Had the same error in v9.5, works fine in v10 if I dont use firebase-functions and strictly use the submodules (firebase-functions/app, /auth, etc)

@HelderSi
Copy link

HelderSi commented Jan 9, 2022

I started to use firebase-admin@^10.0.1 and I had this error when running jest tests. It couldn't map "firebase-admin/app" to "firebase-admin/lib/app" as expected. So I have mapped this manually on jest.config.ts:

import { pathsToModuleNameMapper } from 'ts-jest/utils';
import { compilerOptions } from './tsconfig.json';

...
export default {
 ...
 moduleNameMapper: pathsToModuleNameMapper(
    {
      ...compilerOptions.paths,
      'firebase-admin/*': ['node_modules/firebase-admin/lib/*'],
    },
    {
      prefix: '<rootDir>',
    },
  ),
...
}

That worked for me.

And just to note, my tsconfig.json is like this:

{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "modules/*": [
        "src/modules/*"
      ],
      "shared/*": [
        "src/shared/*"
      ],
    }
  }
}

@alxcholley
Copy link

Hi,
See that : https://firebase.google.com/docs/admin/migrate-node-v10#es-modules-support

@fflores97
Copy link

Similarly to @HelderSi, I had to do a moduleNameMapper config, but I'm using yarn v2 PnP, so my config looks like this:

import { pathsToModuleNameMapper } from "ts-jest/utils";

export default {
  preset: "ts-jest",
  testEnvironment: "node",
  modulePaths: ["<rootDir>/src"],
  moduleNameMapper: pathsToModuleNameMapper({
    "firebase-admin/*": ["firebase-admin/lib/*"],
  }),
};

@Enragedsaturday
Copy link

For some reason npm pulled v9 for me, I manually edited my package.json (remember it's the one in the functions folder):
"firebase-admin": "^10.0.2",
All imports are working correctly now.

@artstylee
Copy link

artstylee commented Feb 2, 2022

backend package json

{
  "name": "back",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.js",
  "dependencies": {
    "bcrypt": "^5.0.1",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "express-validator": "^6.13.0",
    "firebase-admin": "^10.0.2",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^4.1.3",
    "mongoose": "^6.0.12",
    "multer": "^1.4.4",
    "nodemon": "^2.0.14",
    "socket.io": "^4.4.0"
  },
  "scripts": {
    "back": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

node version
v16.13.1
Снимок

firebase library package.json
"version": "10.0.2",

@mattisx
Copy link

mattisx commented Feb 18, 2022

Deleting node_modules, package-lock.json, and running npm cache clean --force fixed this for me on Node 16.14.

@Benjamin-Lee
Copy link

For anyone else looking for things to try, learn from my mistake. When upgrading to firebase-admin@10, I accidentally made it a dev dependency, thus triggering this error.

@Muhkol
Copy link

Muhkol commented Mar 12, 2022

I did have the same issue with not finding the module 'firebase-admin/app'. Ended up accessing firebase products with suggestions from others at the top of this thread. Tried it again the default way from google docs , regardless of the error 'module not found' everything still works fine and able to use firebase product (firestore). You can IGNORE the error and run your code. I am node version 12

@lneninger
Copy link

@Benjamin-Lee that fixed my issue. Thanks for share your error resolution.

@fbukevin
Copy link

This issue is still not solved. Either I use node version 14.6.0 (npm v7.8.0) or version 18.1.0 (npm v8.8.0).

@March-mitsuki
Copy link

I'm using node v18.12.0 with yarn and vscode. Runing yarn cache clean --all then reinstalling yarn install, and restarting vsode fixed this for me.

@jasonburrows
Copy link

Still experiencing this with firebase-admin@11.5.0 and node@18.15.0.

Clearing the cache and re-installing did not help.

I have tried the general import:

import * as firebaseAdmin from 'firebase-admin';

...but I can't get at the getAuth function.

const auth = firebaseAdmin.auth.getAuth(app);

Gives:

Property 'getAuth' does not exist on type '(app?: App | undefined) => Auth'.

@lahirumaramba
Copy link
Member

@jasonburrows If you are using the namespaces you should use firebaseAdmin.auth(app).

I ran a few tests and it seems like import * as firebaseAdmin from 'firebase-admin' imports all the named exports... so you specifically need to access the default export. I am unsure why this happens or what the correct fix for this. I will need to investigate the issue further.

import * as firebaseAdmin from 'firebase-admin';

const auth = firebaseAdmin.default.auth();
[Module: null prototype] {
  default: <ref *1> FirebaseNamespace {
    __esModule: true,
    credential: {
      cert: [Function: cert],
      refreshToken: [Function: refreshToken],
      applicationDefault: [Function: applicationDefault]
    },
    SDK_VERSION: '11.5.0',
    Promise: [Function: Promise],
    INTERNAL: FirebaseNamespaceInternals { appStore: [AppStore] },
    default: [Circular *1]
  }
}

In the meantime, I would also suggest using the new modular syntax:

import { initializeApp, App } from 'firebase-admin/app';
import { getAuth, UserRecord } from 'firebase-admin/auth';

const app: App = initializeApp();

const token: string = await getAuth().createCustomToken('alice');

https://firebase.google.com/docs/admin/migrate-node-v10

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

No branches or pull requests