Firebase Admin Nodejs cannot find module service_account.json

10,700

Solution 1

You are missing the relative portion of the required path. That is, you should doing something like this:

var serviceAccount = require("./service_account.json");

If it's not a relative path, require will be looking in node_modules for a module named service_account.json.

Solution 2

The problem is that the TypeScript compiler does not know about json files. You can tell the compiler about them by adding the following declaration to your typings file.

declare module "*.json" {
  const value: any;
  export default value;
}

You can then import json with:

import * as serviceAccount from './service-key.json';

If you do not already have a typings file setup you will need to create one and then tell tsconfig.json about it by adding it to include or files:

  "include": [
    "./index.d.ts"
  ],
Share:
10,700
Zik
Author by

Zik

Updated on June 16, 2022

Comments

  • Zik
    Zik about 2 years

    I start my node with "node firebasedb.js". My firebasedb.js contains this code:

    var admin = require("firebase-admin");
    
    var serviceAccount = require("service_account.json");
    
    // Initialize Firebase
    var config = {
        credential: admin.credential.cert(serviceAccount),
        apiKey: "<api key>",
        authDomain: "<auth domain>",
        databaseURL: "<database url>",
        storageBucket: "<storage bucket>",
    };
    
    admin.initializeApp(config);
    

    When I run node, I am in the directory where the .json file exists. But it says

    Error: Cannot find module 'service_account.json'
    
  • Karel Debedts
    Karel Debedts over 4 years
    Thank you! could you please give more info about the typings file?
  • phongyewtong
    phongyewtong over 3 years
    where is the typing file? which?
  • Matteo Antolini
    Matteo Antolini over 2 years
    Even with ../service_account.json or with an absolute path, will cause an error. ./service_account,json works