Skip to content

How to connect firebase-admin to the firebase emulators? #776

Closed

Description

@ldiqual

There is a related issue (#575) but it seems that it's still unresolved.

We would like to connect the admin SDK to firebase emulators when running tests. Our setup code looks like this:

import * as admin from 'firebase-admin'
admin.initializeApp({ credential: ... })
export default admin

Then in every file that needs access to firestore, we use:

import firebase from `./firebase`
firebase.firestore().doSomething()

How can we modify this setup so that is connects to the firebase emulators instead?

This is what we've tried so far:

Is there a recommended way to connect the admin sdk to emulators?

Activity

  1. google-oss-bot commented on Jan 30, 2020

    @google-oss-bot

    I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

  2. schmidt-sebastian commented on Jan 31, 2020

    @schmidt-sebastian
    Contributor

    The Admin SDKs support the FIRESTORE_EMULATOR_HOST environment variable. You can simply set it to localhost:8080 to connect directly to the emulator.

    Let us know if you have any other questions, but for now I hope you are unblocked.

  3. fouchekeagan commented on Dec 28, 2020

    @fouchekeagan

    The Admin SDKs support the FIRESTORE_EMULATOR_HOST environment variable. You can simply set it to localhost:8080 to connect directly to the emulator.

    Let us know if you have any other questions, but for now I hope you are unblocked.

    For those in the future, please note this is an environment variable and not a parameter to the admin SDK.
    To elaborate this, if you are running a NodeJS backend/script:

    const useEmulator = true;
    
    if (useEmulator){
        process.env['FIRESTORE_EMULATOR_HOST'] = 'localhost:8080';
    }
    
    admin.initializeApp({ ... });
    

    This will set the environment variable from within code (not recommend for production environments), you can read more in this S.O Article for other ways of setting Environment Variables for NodeJS.

    Do not try to do it this way:

    admin.initializeApp({
        ...
        FIRESTORE_EMULATOR_HOST: 'localhost:8080'
    });
    

    It will have no effect locally, only remotely.

  4. thMthMnky commented on Mar 10, 2021

    @thMthMnky

    I've left a comment in firebase/firebase-tools#2602 (comment) with an admin SDK setup that seems to be working.

  5. FredGithub commented on Feb 18, 2022

    @FredGithub

    In my case (Windows) I was using:

    set GCLOUD_PROJECT="project-id"
    set FIRESTORE_EMULATOR_HOST="localhost:8080"
    node ./index.js
    

    But I didn't realize that when running in PowerShell you need:

    $env:GCLOUD_PROJECT="project-id"
    $env:FIRESTORE_EMULATOR_HOST="localhost:8080"
    node ./index.js
    

    Leaving this here if it helps anyone!

  6. saif97 commented on May 17, 2022

    @saif97

    Side note, setting process.env['FIRESTORE_EMULATOR_HOST'] = 'localhost:8085'; only affects Firestore. Admin calls made to firebase auth WILL go to remote NOT emulator.
    Also, if you don't know what port to set, check firebase.json & look for Firestore port there.

  7. tjad commented on Jul 19, 2022

    @tjad

    Yeah, I'm also looking for how to connect the auth utility of firebase-admin?

    I tried the docs way of doing it with FIREBASE_AUTH_EMULATOR_HOST. I get no errors, however when trying to utilize the sdk, I get "Error while making request: getaddrinfo EAI_AGAIN http. Error code: EAI_AGAIN"

  8. floer32 commented on Jul 26, 2022

    @floer32

    ℹ️ If you're using Firebase Cloud Storage rather than Firestore, you may need to set FIREBASE_STORAGE_EMULATOR_HOST rather than FIRESTORE_EMULATOR_HOST.

  9. tjad commented on Jul 29, 2022

    @tjad

    I managed to get this working after a bit of debugging. As per docs FIREBASE_AUTH_EMULATOR_HOST does work. You should not include the protocol part of the url (http/https)
    e.g: localhost:9099

    not http://localhost:9099

    export FIREBASE_AUTH_EMULATOR_HOST=localhost:9099

  10. johnnyoshika commented on Aug 17, 2022

    @johnnyoshika

    Can we connect to the emulator without relying on an environment variable? The reason why I ask is that I'd like to create 2 instances of the Firesbase Admin app: 1 for Cloud Firestore and 1 for Emulator Firestore so that I can copy data between the 2. For example:

    const cloudAdmin = admin.initializeApp(
      {
        credential: admin.credential.cert(cloudServiceAccount),
      },
      'app-name-1',
    );
    
    const cloudFirestore = cloudAdmin.firestore();
    
    const emulatorAdmin = admin.initializeApp(
      {
        // Connect to Emulator?
      },
      'app-name-2',
    );
    
    const emulatorFirestore = emulatorAdmin.firestore();
    
    (async function () {
      // Copy data from Cloud Firestore to Emulator Firestore
      const data = await cloudFirestore
        .doc('widgets/1')
        .get();
    
      await emulatorFirestore
        .doc('widgets/1')
        .set(data.data());
    })();
    
  11. johnnyoshika commented on Aug 18, 2022

    @johnnyoshika

    The only way I can connect to both the emulator and cloud Firestore in the same script is to use @firebase/testing for the emulator connection and firebase-admin for the cloud connection.

    const firebaseAdmin = require('firebase-admin');
    const testAdmin = require('@firebase/testing');
    
    const cloudFirestore = firebaseAdmin.initializeApp(
      {
        credential: admin.credential.cert(cloudServiceAccount),
      },
      'app-name-1',
    ).firestore();
    
    const emulatorFirestore = testAdmin
      .initializeAdminApp({ projectId: 'demo-project' })
      .firestore();
    
  12. johnnyoshika commented on Nov 21, 2022

    @johnnyoshika

    For anyone else who wants to connect to both the emulator and cloud Firestore at the same time, you can do this. It turns out that process.env.FIREBASE_AUTH_EMULATOR_HOST and process.env.FIRESTORE_EMULATOR_HOST are only referenced when initializing the app.

    const admin = require('firebase-admin');
    
    // Cloud Firestore
    const cloudAdmin = admin.initializeApp(
      { projectId: 'my-cloud-project-id' },
      'cloud-app',
    );
    const cloudDb = cloudAdmin.firestore();
    
    // Emulator
    process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099';
    process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080';
    const emulatorAdmin = admin.initializeApp(
      {
        projectId: 'demo-project',
      },
      'emulator-app',
    );
    const emulatorDb = emulatorAdmin.firestore();
    
    (async () => {
      const cloudDoc = await cloudDb.doc('/documents/one').get();
      const emuDoc = await emulatorDb.doc('/documents/two').get();
    
      console.log('cloudDoc', cloudDoc.data());
      console.log('emuDoc', emuDoc.data());
    })();
    
    
  13. cedvdb commented on Jun 11, 2023

    @cedvdb

    Where are all those variables documented ?

    FIREBASE_AUTH_EMULATOR_HOST, FIRESTORE_EMULATOR_HOST

  14. fouchekeagan commented on Jun 12, 2023

    @fouchekeagan

    @cedvdb they are documented in both GCP and Firestore docs. I've personally found GCP docs to be more technical, while the Firestore docs are more often what you are looking for/will use. Below I linked to the Firestore docs.

    FIREBASE_AUTH_EMULATOR_HOST

    FIRESTORE_EMULATOR_HOST

    These are both sub-sections of the larger documentation for the entire Emulator Suite, I recommend reading everything in the section to strengthen your understanding of the whole Emulators Suite - even when you are confident with the technology, since the docs are often updated with new features.

    Firestore Emulators Suite

  15. dominics commented on Oct 26, 2023

    @dominics

    @johnnyoshika: It turns out that process.env.FIREBASE_AUTH_EMULATOR_HOST and process.env.FIRESTORE_EMULATOR_HOST are only referenced when initializing the app.

    This is true for Firestore, but not true for Firebase Auth (process.env.FIREBASE_AUTH_EMULATOR_HOST).

    Specifically, the AuthResourceUrlBuilder (among other things) calls useEmulator(), which checks process.env.FIREBASE_AUTH_EMULATOR_HOST again (e.g. for deciding the URL format). It does this on many (or all?) of the Firebase Auth methods, not just during app (or auth service) initialization.

    This makes it really hard to run an emulated and non-emulated instance of Firebase Auth from this admin SDK side-by-side in the same process (because both instances are looking at the same piece of global state regularly)

  16. mtrabelsi commented on Dec 30, 2023

    @mtrabelsi

    this worked for me for BOTH auth and firestore!:

    
    // firebaseAdmin.js
    
    import * as admin from 'firebase-admin';
    
    if (!admin.apps.length) {
      // Connect to Firestore emulator if in development environment
      if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
        //for firestore
        process.env['FIRESTORE_EMULATOR_HOST'] = '127.0.0.1:1956';
        //for auth
        process.env['FIREBASE_AUTH_EMULATOR_HOST'] =  '127.0.0.1:9099';
        }
    
        admin.initializeApp({
            credential: admin.credential.cert({
                projectId: process.env.FIREBASE_PROJECT_ID,
                clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
                privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
            }),
            databaseURL: process.env.FIREBASE_DATABASE_URL,
        });
    }
    
    export default admin;
    
    
  17. Amirjab21 commented on Apr 3, 2024

    @Amirjab21

    This emulator should be its own npm package - having to add a global package just to test database is not ideal.

  18. maxiedaniels commented on May 31, 2024

    @maxiedaniels

    Ah very nice I was trying to figure out auth emulator for my backend, this answers it. But one question - do I still have to provide a valid config? I was under the impression the emulator of this was so I didn't have to create a second Firebase app for development..

  19. falk-stefan commented on Oct 16, 2024

    @falk-stefan

    How can I verify that the emulator is actually being used?

    I am sending a JWT token from my web client (it's using the Firebase Auth Emulator) to my backend.

    However, whily calling verifyIdToken(), I am getting the following error:

    {
      errorInfo: {
        code: 'auth/invalid-credential',
        message: 'Must initialize app with a cert credential or set your Firebase project ID as the GOOGLE_CLOUD_PROJECT environment variable to call verifyIdToken().'
      },
      codePrefix: 'auth'
    }
    

    Does this imply, that firebase-admin is not using the emulator?

    I am running the server with

    FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9099
    FIRESTORE_EMULATOR_HOST=127.0.0.1:9199
    
  20. bespy commented on Jan 17, 2025

    @bespy

    Just supplying a stub for the Credential interface works, as the token is never verified.

    import admin from 'firebase-admin'
    
    process.env.GCLOUD_PROJECT = 'demo'
    process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099'
    
    const demoApp = admin.initializeApp({
        credential: {
            getAccessToken: () => Promise.resolve({access_token: 'foo', expires_in: 3600}),
        },
        databaseURL: 'http://localhost:9000/?ns=demo-default-rtdb',
    })
    
    await demoApp.auth().listUsers()
        .then(l => console.log(l))
    
    await demoApp.database().getRules()
        .then(r => console.log(r))

    credit: #2034

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

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions