We use Firebase for authentication in our web apps, and I've built an API proxy to retrieve all the authenticated users from Firebase.
-
You need Firebase service account json file. Login into your Firebase Project Account, Go to Project settings → Services Accounts → Generate new private key. Save that json file in a folder in app/files.
-
Install the firebase SDK package.
terminal
Copynpm install firebase-admin
- Open server.js file and add two lines in this file.
JavaScript
Copy// server.js const firebaseProxyRoutes = require('./app/routes/firebaseProxyRoutes'); app.use('/firebase/proxy', firebaseProxyRoutes);
- Create a route file in the app/routes directory named firebaseProxyRoutes.js
JavaScript
Copy// app/routes/firebaseProxyRoutes.js const express = require('express'); const router = express.Router(); const firebaseController = require('../controllers/firebaseController'); router.get('/auth/users', firebaseController.authUsers); module.exports = router;
- Create a controller file in the app/controllers directory named firebaseController.js
JavaScript
Copy// app/controllers/firebaseController.js const { responseList } = require('../errors/responseList'); const admin = require('firebase-admin'); const serviceAccount = require('path/to/firebase-adminsdk-private-key.json'); // Initialize Firebase Admin SDK admin.initializeApp({ credential: admin.credential.cert(serviceAccount), }); const auth = admin.auth(); // List firebase auth users exports.authUsers = async (req, res) => { const { limit, pageToken } = req.query; try { let listUsersResult; if (pageToken) { listUsersResult = await auth.listUsers(limit || 100, pageToken); } else { listUsersResult = await auth.listUsers(limit || 100); } const users = listUsersResult.users.map((userRecord) => userRecord.toJSON() ); res.status(200).send({ users, pageToken: listUsersResult.pageToken }); } catch (error) { res.status(500).send(responseList(500, error.message)); } };
Now the API is ready to get Firebase Auth Users as JSON.
Copyhttp://localhost:3001/firebase/proxy/auth/user