简体   繁体   中英

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.

Yes, you can access Firebase Realtime Database from both client-side Node.js and server-side Node.js. But the SDK are separate, and you can't include both of them in a single project. The latter seems to be what is leading to the error you now have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM