首页 > 解决方案 > Is it possible to access firebase on both server side and client side in NodeJS?

问题描述

I'm working an app that need to access the firebase database on both client-side (to catch "on" event to grab recently added data) and server-side (to add record to the database). I'm not sure that I did it correctly that use 2 db instances are required on both client and server OR create 1 on the server and use it on the client cause I got a warning on the local side saying that Firebase is already defined in the global scope.

This is how I declare the db instance on server-side, this works perfectly fine:

var admin = require("firebase-admin");
var serviceAccount = require("../config/sterminal-0000-firebase-adminsdk-bvuit-ce5ee771bc.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://sterminal-0000.firebaseio.com"
});

module.exports.admin = admin;

...

const {admin} = require('../extra/firebase');
let db = admin.database();

This is how I declare the db instance on client-side:

Include the libs to pug template

script(src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js")
script(src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js")
script(src="/javascripts/local.js" crossorigin="anonymous")

And in local script:

var firebaseConfig = {
    apiKey: "AIzaSyCkip7lcHNNodJNhrO5n0Hog5Kvs100000",
    authDomain: "sterminal-00000.firebaseapp.com",
    databaseURL: "https://sterminal-00000.firebaseio.com",
    projectId: "sterminal-8bf73",
    storageBucket: "sterminal-00000.appspot.com",
    messagingSenderId: "961511900000",
    appId: "1:96151100000:web:f3cec40f38f7b7d4000000"
};

firebase.initializeApp(firebaseConfig);

firebase.database().ref("messages").on("child_added", function (snap) {
        console.log(snap.val().message);
}); // ----> DOES NOT WORK

I got a warning on local-side:

logger.ts:115 [2020-04-27T18:43:48.559Z]  @firebase/app: 
    Warning: Firebase is already defined in the global scope. Please make sure
    Firebase library is only loaded once.

标签: node.jsfirebaseexpressfirebase-realtime-database

解决方案


是的,您可以从客户端 Node.js 和服务器端 Node.js 访问 Firebase 实时数据库。但是 SDK 是独立的,您不能将它们都包含在一个项目中。后者似乎是导致您现在遇到的错误的原因。


推荐阅读