简体   繁体   English

如何在 next.js 中使用 firebase 的 firestore/admin sdk

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

I am building an application with firebase and next.js我正在用 firebase 和 next.js 构建一个应用程序

I am fairly new to this set up, completely new to SSR, and the firebase docs are confusing me.我对这个设置相当陌生,对 SSR 完全陌生,firebase 文档让我感到困惑。

Currently, I am using firebase functions to run next.js, and that works like a charm.目前,我正在使用 firebase 函数来运行 next.js,这就像一个魅力。 But now, I want to use firestore.但是现在,我想使用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.第一个是“网络”解决方案,它对我没有好处,因为我相信它不是 SSR,而我的应用程序的全部意义就在于此。

The other one is the 'node.js' solution, which runs on the firebase functions, this makes a lot more sense to me.另一个是“node.js”解决方案,它在 firebase 函数上运行,这对我来说更有意义。 The part I can't figure out, is using it with Next.js我无法弄清楚的部分是将它与 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?在我当前的设置中,我正在将我的 next.js 应用程序构建函数文件夹中,在函数文件夹中,我可以引用我使用“node.js”解决方案创建的 databaseref 对象,但是如何构建我的下一个应用程序之前引用它? 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:functions/index.js里面我可以这样做:

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?)并使用db读取并添加到 Firestore、服务器端(对吗?)

but all my code is in src/ before I build it and I don't think I could use it there.但是我所有的代码在构建之前都在src/ ,我认为我不能在那里使用它。 Should I structure my project differently?我应该以不同的方式构建我的项目吗? Or what should I do to be able to use db ?或者我应该怎么做才能使用db Or, of course, another way to have a server side connection with my firestore.或者,当然,另一种与我的 Firestore 建立服务器端连接的方法。

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.我正在寻找更可爱的 cookie 代码,但发现您的问题没有得到解答。

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.至少这就是我使用 firebase-admin 所做的。 Notice here my answer is bad becase I acyually interfcae wit my client through socket.io.请注意,我的回答很糟糕,因为我通过 socket.io 与我的客户进行了交流。 I only use firebase for client code and authentication我只将 firebase 用于客户端代码和身份验证

In package.json you are adding the script tag to stratfrom the command line在 package.json 中,您将脚本标记添加到 stratfrom 命令行

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

that makes it so you can run这样你就可以跑了

$ npm run server

from the command line从命令行

~/package.json ~/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.在 server.js 文件中,您为服务器端渲染加载 express,可能可以使用另一篇文章启动您自己的 http 服务器。 However, as seen below I actullay use socket.io so it has that connection details the key is right here thogh但是,如下所示,我实际使用 socket.io,因此它具有连接详细信息,关键就在这里

he nextHandler() passes the control of the server to the next. nextHandler() 将服务器的控制权传递给下一个。 So you can probably start an http server and use nextHandler()所以你可以启动一个 http 服务器并使用 nextHandler()

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

~/server.js 〜/ 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'));
        })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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