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

1

7

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.

Hoseahoseia answered 10/6, 2019 at 2:18 Comment(1)
Have you come up with solution? i am also working on next.js and firebase and dont have idea how to use custom claims as it says that use in node.js. may i call it in api folder or whatBakki
W
1

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'));
        })
Winged answered 24/3, 2020 at 22:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.