【问题标题】:How to make Firestore query during SSR如何在 SSR 期间进行 Firestore 查询
【发布时间】:2022-10-24 14:55:17
【问题描述】:

我想在服务器端渲染期间从 Firestore 获取数据。我知道我可以使用REST API(并将令牌附加到请求的标头),但我不想在服务器端编写 REST 请求,然后使用standard Firestore queries 在客户端复制相同的请求。在客户端上,由于实时更新,我更喜欢标准查询(无 REST)。而且我想在服务器上重用来自客户端的查询(即使没有实时更新的好处)。

我在服务器上手动验证令牌:

import admin from 'firebase-admin';
import { initializeApp, getApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseApp = initializeApp(config);
const db = getFirestore(firebaseApp);

const decodedIdToken = await admin.auth().verifySessionCookie(sessionCookie);
// => token verified: decodedIdToken.userId = "xxx"

但是当我想执行查询时:

import { collection, getDocs } from 'firebase/firestore';

const querySnapshot = await getDocs(collection(db, 'myCollection'));

我得到错误:

{
  "code": "permission-denied",
  "name": "FirebaseError"
}

Firestore 规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

在客户端,可以使用onAuthStateChanged 解决错误,但我不能在服务器上使用此侦听器。

有没有办法使用手动验证的令牌运行 Firestore 查询?

【问题讨论】:

  • 您能否根据此documentation 为您的项目提供 Firestore 规则?
  • @RobertG 问题已根据规则更新。

标签: firebase google-cloud-firestore firebase-authentication server-side-rendering


【解决方案1】:

我设法复制了您的错误。您收到此错误是因为您尝试使用客户端 SDK 而不是 firebase-admin

这是供您参考的示例代码:

import admin from 'firebase-admin';
import { initializeApp } from 'firebase-admin/app';
import { getFirestore } from "firebase-admin/firestore";

const firebaseApp = initializeApp(config);
const db = getFirestore(firebaseApp);

// const decodedIdToken = await admin.auth().verifySessionCookie(sessionCookie);
// => token verified: decodedIdToken.userId = "xxx"

// const querySnapshot = await getDocs(collection(db, 'myCollection'));
db.collection("myCollection").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});

我使用了version 8(commonJS)而不是version 9(模块化),因为firebase-admin 仍然使用点符号语法。

[sampleQuery]  =>  { test: 'testing' }

这是how to get all documents in a collection 上的链接。

这是upgrading to Node.js SDK Admin SDK v10 (modular SDK) 上的另一个参考。

让我知道这是否适合您,或者您是否想改用客户端 SDK。

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 2018-06-17
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多