How to connect `firebase-admin` to the firebase emulators?
There is a related issue (https://github.com/firebase/firebase-admin-node/issues/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:
- Have the setup code return the
@firebase/testingnamespace depending on the node environment. However this library doesn't setup a default firebase app so callingfirebase.firestore()fails. - Have
firebase-adminconnect to the emulators directly, by providing an explicitdatabaseURLand firestore URLs, and overridingcredential.getAccessToken()to returnowner. Now the issue is that the admin's implementation of firestore expects a service account and throws on the credentials override: https://github.com/firebase/firebase-admin-node/blob/master/src/firestore/firestore.ts#L95-L100 - Return the firebase app as part of the setup code, so that
app.firestore()always works. This requires refactoring the whole codebase to use an app instance instead of a firebase workspace.
Is there a recommended way to connect the admin sdk to emulators?
I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.
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.
The Admin SDKs support the FIRESTORE_EMULATOR_HOST environment variable. You can simply set it to
localhost:8080to 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.
I've left a comment in https://github.com/firebase/firebase-tools/issues/2602#issuecomment-795075399 with an admin SDK setup that seems to be working.
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!
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.
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"
ℹ️ If you're using Firebase Cloud Storage rather than Firestore, you may need to set FIREBASE_STORAGE_EMULATOR_HOST rather than FIRESTORE_EMULATOR_HOST.
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
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());
})();
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();
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());
})();
Where are all those variables documented ?
FIREBASE_AUTH_EMULATOR_HOST, FIRESTORE_EMULATOR_HOST
@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.
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.
@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)
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;
This emulator should be its own npm package - having to add a global package just to test database is not ideal.
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..
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
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: https://github.com/firebase/firebase-admin-node/issues/2034