I'm trying to figure out how Firebase works when I've got a client-server model. Usually the client performs a login/register request to the server. Firebase documentation https://firebase.google.com/docs/auth/web/start?hl=en&authuser=0 shows how to register/login, but is the code meant for the client? Other sources suggest this, but can I run "createUserWithEmailAndPassword" and "signInWithEmailAndPassword" on the server side?
My server (written in express and node) now ends up looking like this:
import { initializeApp as adminInitializeApp, applicationDefault} from 'firebase-admin/app';
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
};
// Initialize Firebase
const fireApp = initializeApp(firebaseConfig);
const fireAppAdmin = adminInitializeApp({
credential: applicationDefault(),
});
// const analytics = getAnalytics(fireApp);
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
const auth = getAuth();
.....
app.post("/auth/register", async (req, res) => {
createUserWithEmailAndPassword(auth, req.body.email, req.body.password)
.then((userCredential) => {
// Signed up
const token = userCredential.user.getIdToken();
res.status(200).send({
token,
});
Where the admin is needed for me to verify tokens sent back from the client. Is this the right approach?
can I run "createUserWithEmailAndPassword" and "signInWithEmailAndPassword" on the server side?
Yes, you can. But they're not intended to be used that way. Those are supposed to be used from the client side, not from the server.
It just depends on your use case. You can, for example:
Use createUserWithEmailAndPassword
from the client (using the Firebase Client SDK). Set up an auth trigger on the server side, so you can listen to user creation events and react to them (like sending a welcome email, for example).
If you don't want to allow users to create their own accounts from the client side, you can create an endpoint (with a callable function, for example), so your clients send a request to the server. Then, the server verifies and does whatever you need, and it ends up creating the auth user account (from the server, using the Firebase Admin SDK to create the user in the Firebase Authentication service).
In both case you'll end up with a new user in the Firebase Auth service.
So, firebase
is the JavaScript Client SDK.
And firebase-admin
is the JavaScript Admin (server) SDK.
Where the admin is needed for me to verify tokens sent back from the client. Is this the right approach?
Actually, if you use Firebase Callable Function it takes care of verifying the token for you. Clients will get 401 Unauthorized error if they invoke with an invalid token. Your server onCall()
function gets triggered only when the request token validation is successful.