Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use firebase's firestore/admin sdk with next.js

I am building an application with firebase and next.js

I am fairly new to this set up, completely new to SSR, and the firebase docs are confusing me.

Currently, I am using firebase functions to run next.js, and that works like a charm. But now, I want to use firestore. I see two ways to use it in my project according to the docs (if I get it right). The first one is the 'web' solution which would not be benificial for me, because I believe it is not SSR, while the whole point of my app is being just that.

The other one is the 'node.js' solution, which runs on the firebase functions, this makes a lot more sense to me. The part I can't figure out, is using it with Next.js

In my current set up I am building my next.js application to the functions folder, inside the function folder I can reference the databaseref object I create with the 'node.js' solution, but how can I reference this before building my next application? So when I'm not in the functions folder?

Setup:

- src
  - utils
  - pages
    - index.js
    - signin.js
    - // etc.
- functions 
  - next // this is the output folder of my 'src' build
  - index.js 
  - // etc.

inside functions/index.js I could do:

const admin = require('firebase-admin');
const functions = require('firebase-functions');

admin.initializeApp(functions.config().firebase);

let db = admin.firestore();

and use db to read and add to firestore, serverside (right?)

but all my code is in src/ before I build it and I don't think I could use it there. Should I structure my project differently? Or what should I do to be able to use db? Or, of course, another way to have a server side connection with my firestore.

like image 436
Robbeoli Avatar asked Jun 10 '19 02:06

Robbeoli


People also ask

How do I get data from firestore on next JS?

import firebase from 'firebase/compat/app'import 'firebase/compat/firestore'// For Firebase JS SDK v7. 20.0 and later, measurementId is optional// Here comes your firebase configrationif(!

How do I connect next javascript to Firebase?

First, go to the Firebase console and Add project. Enter the preferred name of your project, i.e., next-js-todos-app . Then click continue. Then Configure Google Analytics and click continue.

Does Firebase support next JS?

“Firebase Hosting provides fast and secure hosting for your web app, static and dynamic content, and microservices. Next. js is very awesome react framework to build applications, mostly preferred for its most useful feature, Server Side Rendering . It is very easy to learn and use for the react developers.


1 Answers

Sorry for the bad answer. It's my first time. I was looking for cookie cuter code and seen that uor question wasn't answered.

I don't know the proper jargon. Yet, you have t run your app wit a custom server. Atleast that's wjhat I do to use firebase-admin. Notice here my answer is bad becase I acyually interfcae wit my client through socket.io. I only use firebase for client code and authentication

In package.json you are adding the script tag to stratfrom the command line

{
    "scripts:
        "server": "node server.js"
}

that makes it so you can run

$ npm run server

from the command line

~/package.json

    {
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
  "server": "node server.js",
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "9.3.1",
    "react": "16.13.1",
    "react-dom": "16.13.1"
  }
}

In the server.js fil you load up express for a server side rendering, probably can start your own http server with another post. However, as seen below I actullay use socket.io so it has that connection details the key is right here thogh

he nextHandler() passes the control of the server to the next. So you can probably start an http server and use nextHandler()

  app.get('*', (req, res) => {
                return nextHandler(req, res)
            })

~/server.js

    const fs = require('fs');
    const express = require('express');
    const app = express();
    const server = require('http').Server(app)
    const firebaseAdmin = require('./services/dwf.firebase.admin.js');
    const secureServer = require('https').createServer({
        key: fs.readFileSync('./key.pem'),
        cert: fs.readFileSync('./cert.pem')
    }, app)
    const io = require('socket.io')(secureServer, {secure: true})

    const User = require('../../users/user.manager.js');
    let user = User(io,firebaseAdmin.auth(),firebaseAdmin.database());

    const next = require('next')

    const dev = process.env.NODE_ENV !== 'production'
    const nextApp = next({dev})
    const nextHandler = nextApp.getRequestHandler()

    // socket.io server
    io.on('connection', socket => {
        console.log(`Main Socket Opened by:\n ${socket.id}`);
        socket.on('getDb',function(userId,refs,fn){
        console.log("Getting Data")
            firebaseAdmin.database().ref(refs).once('value',(snapshot)=>{
                console.log(snapshot.val());
                fn({body: snapshot.val()})
                socket.emit('getDb',snapshot.val());
            });
        })
        socket.on('disconnect', () => {
            console.log(`Main Socket Closed by:\n ${socket.id}`);
        });
    })

    nextApp
        .prepare()
        .then(() => {
            app.get('/data/messages', (req, res) => {
                res.json(messages)
            })
            app.get('*', (req, res) => {
                return nextHandler(req, res)
            })
            secureServer.listen(PORT, () => console.log('#> Main Server ready for clients on https://0.0.0.0:PORT'));
        })
like image 94
user9407039 Avatar answered Oct 09 '22 02:10

user9407039