I am trying to get going with firebase (auth only) in a node.js server but I am running into errors even getting started.
I believe I am following the Google docs exactly for their section "Add Firebase to a server" here: https://firebase.google.com/docs/admin/setup . Additionally I've read every stackoverflow that pops up in the first few pages of Google search and multiple tutorial sites for firebase-admin + nodejs. Yet cannot seem to get past what seems to be a simple step here.
The specific error I get is:
Error authenticating user: FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app).
When I try the following (again trying to matchup to what the docs show):
.env:
GOOGLE_APPLICATION_CREDENTIALS="firebase-svc-acct.json"
(where firebase-svc-acct.json is the service account key for the project obtained as per those same google docs under "Initialize the SDK in non-Google environments")
index.ts (node server entry):
...
import { initializeApp, applicationDefault } from "firebase-admin/app";
...
initializeApp({
credential: applicationDefault(),
});
AuthController.ts (temporary testing, wired up with express router that is not shown here for brevity, trust me it gets here):
...
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
...
loginFirebaseTest = async (req: Request, res: Response): Promise<void> => {
const { email, password } = req.body;
const auth = getAuth(); // <------------------ Error is thrown here
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log(
"Successfully authenticated user:",
userCredential.user.uid
);
res.status(200).json({ message: "User login successful" });
})
.catch((error) => {
console.log("Error authenticating user:", error);
res.status(401).json({ error: "Invalid credentials" });
res.send();
});
};
As discovered in comments to the original question I was just thinking about firebase completely wrong. Unlike is common when you bake your own auth you won't be passing the email + password over to firebase and handing back a token. The client does that directly to firebase.
So in the backend instead you just start accepting/checking the token - you don't need a login endpoint and you would do that with firebase-admin in nodejs (firebase/auth is for the front end).
Getting into how to authenticate in specific gets outside of the scope of the issue presented here but I found https://www.toptal.com/firebase/role-based-firebase-authentication to do a decent introduction.