0
votes

I'm trying to connect Nuxt 2.14 with firebase firestore
I'm writing a plugin for firebase that runs on the server
I'm using "inject" to pass firebase.firestore() object as db.

But, when I'm using the $db I just injected
and try to make a data variable equal to $db via asyncData,

I get an error:
"Maximum call stack size exceeded"


I guess the firebase.firestore() object has a "circular structure"
Any suggestions?
Should I approach this differently?
Thank you

Here is the code for the different files I'm using:

.env

FB_DB_PATH=XXXXXX
FB_API_KEY=YYYYYY
FB_PROJECT_ID=ZZZZZZ
FB_AUTH_DOMAIN=EEEEEEE

nuxt.config.js

plugins: [
    { src: '~plugins/firebase.js', mode: 'server' }, 
    // runs on server to get the firebase privateRuntimeConfig params

],
  
publicRuntimeConfig: {
  baseURL: process.env.BASE_URL // just for test
    
},
privateRuntimeConfig: {
  fbProjectID: process.env.FB_PROJECT_ID,
  fbDBPath: process.env.FB_DB_PATH,
  fbApiKey: process.env.FB_API_KEY,
  fbAuthDomain: process.env.FB_AUTH_DOMAIN
},

firebase.js - this is the plugin file

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

export default function (context, inject) {
   
  if (!firebase.apps.length) {

    firebase.initializeApp({
      apiKey: context.$config.fbApiKey,
      authDomain: context.$config.fbAuthDomain,
      //databaseURL: context.$config.fbDBPath,
      projectId: context.$config.fbProjectID
    })
    
  }
  
 let auth = firebase.auth();
 let db = firebase.firestore();

 inject('db', db);
}

in page code:

asyncData ( context ) {
      return { db: context.$db }
}
1

1 Answers

0
votes

AFAIK, what you're trying to do won't work, and is not secure anyways. Injecting your Firebase auth and firestore will inherently expose the API key client side, because they still need to use it there to communicate with the Firebase.

Further, passing back an object with circular references doesn't work, as Vue cannot serialize it properly, and wouldn't know how to deserialize it on the client either.

If you're just fetching data from Firebase at page load, then you should do so in the asyndData method, and return the fetched data. However, if you need to make calls during runtime, such as storing user data, then you will need an API to keep the keys secure. I usually recommend starting with Nuxts serverMiddleware, as it works out of the box on Nuxt projects.