Skip to content

Does Firebase Admin SDK support Firestore Emulator? #575

Closed

Description

@ChromeQ

I have a project using firestore, functions and hosting.
Until recently I was happily working locally with firebase serve --only functions,hosting and that would work with the production firestore.
Using the new firestore emulator I read loads suggesting to use emulator over serve, and my functions have firestore triggered functions which I would like to test locally.

When I firebase serve --only functions I get a Ignoring trigger "onDocumentCreate" because the Cloud Firestore emulator is not running. This suggests the trigger can work with the emulator.
When I have the firestore emulator running in another process, the functions serve does not detect the firestore emulator running.
So finally I try firebase emulators:start --only firestore,functions which starts up fine with all triggers.

As soon as Firestore code is executed I get the error:

Google API requested!
    - URL: "https://oauth2.googleapis.com/token"
    - Be careful, this may be a production service.
>  { Error: Getting metadata from plugin failed with error: Header field "authorization" must have only a single value
>      at Http2CallStream.call.on (/home/dav/dev/lms/functions/node_modules/@grpc/grpc-js/build/src/call.js:68:41)
>      at emitOne (events.js:121:20)
>      at Http2CallStream.emit (events.js:211:7)
>      at process.nextTick (/home/dav/dev/lms/functions/node_modules/@grpc/grpc-js/build/src/call-stream.js:71:22)
>      at _combinedTickCallback (internal/process/next_tick.js:132:7)
>      at process._tickCallback (internal/process/next_tick.js:181:9)
>    code: 'ERR_HTTP2_HEADER_SINGLE_VALUE',
>    details: 'Getting metadata from plugin failed with error: Header field "authorization" must have only a single value',
>    metadata: Metadata { options: undefined, internalRepr: Map {} } }

How can I make firebase-admin work with emulated firestore and functions?

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

admin.initializeApp();
const firestore = admin.firestore();

const foo = firestore.collection('colName').doc('docId')
    .onSnapshot(snap => {
        console.log(snap);
    });

Using all the latest packages:

    "firebase-admin": "^8.1.0",
    "firebase-functions": "^3.0.1",
    "firebase-tools": "^7.0.0",

OS: Linux Ubuntu 18.04
NPM version: 6.9.0
Node version: 8.15.0

Activity

  1. google-oss-bot commented on Jun 19, 2019

    @google-oss-bot

    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.
  2. schmidt-sebastian commented on Jun 19, 2019

    @schmidt-sebastian
    Contributor

    @ChromeQ The easiest way to achieve this to use the recent version of @google-cloud/firestore. Starting with version 2.2, we support the environment variable FIRESTORE_EMULATOR_HOST. If you set this environment variable to the host entry provided at emulator startup (such as localhost:8080), Firestore will connect to the emulator instead of to the backend.

  3. ChromeQ commented on Jun 19, 2019

    @ChromeQ
    Author

    Thanks, but that also didn't work as I get another problem:
    npx firebase emulators:start --only firestore runs in one process and shows FIRESTORE_EMULATOR_HOST=localhost:5002

    Then in a new process I run:
    FIRESTORE_EMULATOR_HOST=localhost:5002 npx firebase serve --only functions

    Your code has been provided a "firebase-admin" instance.
    ⚠  Error: Cannot set both "settings.host" and "settings.servicePath".
        at Firestore.validateAndApplySettings (/home/dav/dev/lms/functions/node_modules/@google-cloud/firestore/build/src/index.js:353:23)
        at Firestore.settings (/home/dav/dev/lms/functions/node_modules/@google-cloud/firestore/build/src/index.js:339:14)
        at initializeSettings (/home/dav/dev/lms/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:238:33)
        at Proxy.<anonymous> (/home/dav/dev/lms/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:269:21)
        at Object.<anonymous> (/home/dav/dev/lms/functions/index.js:43:11)
        at Module._compile (module.js:653:30)
        at Object.Module._extensions..js (module.js:664:10)
        at Module.load (module.js:566:32)
        at tryModuleLoad (module.js:506:12)
        at Function.Module._load (module.js:498:3)
    ⚠  Your function was killed because it raised an unhandled error.
    
  4. schmidt-sebastian commented on Jun 19, 2019

    @schmidt-sebastian
    Contributor

    We will get that fixed! Sorry for the trouble.

  5. ChromeQ commented on Jun 19, 2019

    @ChromeQ
    Author

    Thanks, but ideally it would work with simply: firebase emulators:start --only firestore,functions or firebase serve --only firestore,functions
    Can it be fixed to work like that without the need of the extra variable or extra process running firestore emulator?
    Thanks

  6. hiranya911 commented on Jun 21, 2019

    @hiranya911
    Contributor

    @schmidt-sebastian where did we land with this one?

  7. 12 remaining items

  8. ryanpbrewster commented on Aug 26, 2019

    @ryanpbrewster

    That's clever. Thanks for posting this!

    The alternative is to set the environment variable outside of the script itself.

    export FIRESTORE_EMULATOR_HOST="localhost:8080"
    npm test
    

    We have documentation in the works for all of these SDKs. There are quite a few of them, and we wanted to make sure the experience was similar across the board. Be on the lookout for comprehensive docs on using the Firebase emulator suite.

  9. Elyx0 commented on Nov 8, 2019

    @Elyx0

    I'm hitting the same problem here
    with firebase emulators:start --only functions,database,firestore

    'use strict';
    import 'jest';
    
    process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080';
    process.env.FIREBASE_DATABASE_EMULATOR_HOST = 'localhost:9000';
    
    // INIT ---------------------------------------------------------------------------------- 
    import * as functions from 'firebase-functions';
    import * as functionsTest from 'firebase-functions-test';
    import * as admin from 'firebase-admin';
    admin.initializeApp();
    

    But then any code calling admin throws with Can't determine Firebase Database URL.
    I run my tests with

    FIREBASE_DATABASE_EMULATOR_HOST=localhost:9000 FIRESTORE_EMULATOR_HOST=localhost:8080 jest --watchAll --coverage
    

    I see from a4ad828 that one of the env override got removed, am I missing something?

  10. Elyx0 commented on Nov 8, 2019

    @Elyx0

    With "@firebase/testing"; it sets it up correctly

    admin.initializeTestApp({ projectId, databaseName, auth })
    admin.initializeAdminApp({ projectId, databaseName, auth })
    

    The problem is that most of my code relies on

    import * as admin from 'firebase-admin';
    

    in each file for doing the database management, so I can't mock it

    Should I add a wrapper around my admin that exports the one from firebase/testing if in test mode to my functions and another to live mode from the firebase-admin ? It feels contrived since I have a correct emulator running...

  11. Elyx0 commented on Nov 8, 2019

    @Elyx0

    I ended up doing something like that:

    import * as admin from 'firebase-admin';
    import * as adminTesting from "@firebase/testing";
    
    
    const databaseName = "database-emulator-example";
    const projectId = "firestore-emulator-example";
    export const coverageUrl = `http://localhost:9000/.inspect/coverage?ns=${databaseName}`;
    
    export type finalExportUnionType = typeof admin | firebase.app.App;
    export let finalExport: finalExportUnionType = admin;
    if (process.env.NODE_ENV == 'test') {
     console.log('From test mode');
     const adminApp = adminTesting.initializeAdminApp({projectId, databaseName});
     finalExport = adminApp;
    }
    

    But it feels like an ugly hack

  12. akauppi commented on Jun 25, 2020

    @akauppi

    Though this is closed, this may help someone:

    If you're wanting to use the Admin SDK with the new Emulator UI, make sure you set up projectId parameter to match your Firebase project. Otherwise, data gets written somewhere, but isn't visible in the emulator.

  13. milan-codes commented on Jul 12, 2020

    @milan-codes

    Still facing this issue, even though the FIREBASE_DATABASE_EMULATOR_HOST env variable is set (as it is stated here), I still can't get Admin SDK to connect to the emulators. Tried @akauppi 's suggestion, but still no success.

  14. schmidt-sebastian commented on Jul 14, 2020

    @schmidt-sebastian
    Contributor

    @milan-codes Most of the advice here is for the Firestore emulator.

    There is currently a known bug with the Database emulator setting: firebase/firebase-js-sdk#3144
    Do you see errors similar to the ones reported there?

  15. milan-codes commented on Jul 14, 2020

    @milan-codes

    @schmidt-sebastian Thanks for pointing me to the right issue! That issue seems to be similar to mine, but now I had the chance to test my code on a Windows PC. Everything works fine there, it successfully connects to the emulator. I have no idea why it doesn't work on my mac. Should I open a new issue for this?

  16. schmidt-sebastian commented on Jul 15, 2020

    @schmidt-sebastian
    Contributor

    #3144 is merged and should be released this week. I suggest to wait a couple days before trying to repro.

  17. habibKadiri commented on Nov 17, 2020

    @habibKadiri

    Ok, I finally figured this out, I wish someone at google would document this better because in the end, it isn't very hard to setup...

    Start the emulator:

    firebase emulators:start --only firestore

    import {clearFirestoreData} from "@firebase/testing";
    import * as admin from "firebase-admin";
    
    process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080';
    
    const app = admin.initializeApp({
    	projectId: 'test',
    	credential: admin.credential.applicationDefault()
    });
    
    describe("test", () => {
    	beforeEach("reset the database", async () => {
    		await clearFirestoreData({projectId: app.options.projectId || ''});
    	});
    
    	it("works", async () => {
                // write some tests against the admin sdk firestore
               app.firestore()....
    	});
    });

    You are a god send, thank you good sir!

  18. ir-fuel commented on Mar 11, 2021

    @ir-fuel

    FYI @firebase/testing has been deprecated

  19. lookfirst commented on Mar 11, 2021

    @lookfirst

    FYI @firebase/testing has been deprecated

    what's the replacement?

  20. schmidt-sebastian commented on Mar 16, 2021

    @schmidt-sebastian
    Contributor
  21. vladfaust commented on Jul 27, 2021

    @vladfaust

    Please answer if current release supports managing multiple tenants with Emulators? I currently get such a error:

     Error: An internal error has occurred. Raw server response: "{"error":{"code":404,"message":"Not Found","errors":[{"message":"Not Found","reason":"notFound"}],"status":"NOT_FOUND"}}"
        at FirebaseAuthError.FirebaseError [as constructor] (C:\Users\Vlad\Development\Desklify\functions\node_modules\firebase-admin\lib\utils\error.js:44:28)
    

    for any tenant-related activity, such as app.auth().tenantManager().listTenants().

    I tried everything: setting databaseURL, process.env.FIREBASE_AUTH_EMULATOR_HOST = "localhost:9099" and process.env.FIRESTORE_EMULATOR_HOST = "localhost:8080". Still no luck.

    Thanks in advance!

    UPD: I tried to do the following via Postman: GET http://localhost:9099/identitytoolkit.googleapis.com/v2/projects/<project name>/tenants; still getting the 404 response.

  22. SUVOLewis commented on Aug 3, 2021

    @SUVOLewis

    @vladfaust When trying to create a new user under a specific tenant, I get the following:

    "{"error":{"code":501,"message":"identitytoolkit.projects.tenants.accounts is not implemented in the Auth Emulator.","errors":[{"message":"identitytoolkit.projects.tenants.accounts is not implemented in the Auth Emulator.","reason":"unimplemented"}],"status":"NOT_IMPLEMENTED"}}"
    

    I think it's safe to assume that the Google Cloud Identity Platform Tenant System is not yet a part of the Firebase Auth Emulator.
    Currently, I'm unaware of any alternatives to this.

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