You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13如何用Fetch从Firestore取数据并配置缓存

使用Next.js Fetch API结合Firebase Firestore实现缓存数据获取

要替换原有Firebase SDK调用,改用Next.js Fetch API实现带缓存的数据获取,核心是通过Firestore的REST API发起请求,并利用Next.js扩展的Fetch配置控制缓存行为,具体实现如下:

1. 准备Firestore REST API端点

Firestore的REST查询端点格式固定,需替换为你的项目信息:

https://firestore.googleapis.com/v1/projects/{你的Firebase项目ID}/databases/(default)/documents/{集合名}?q={查询条件}
  • 替换{你的Firebase项目ID}为实际项目ID(可在Firebase控制台查看)
  • 替换{集合名}为存储文章的集合名称(比如posts)
  • 查询条件按Firestore语法编写:比如筛选tag字段等于传入的name,需写成tag='${name}'(字符串值必须用单引号包裹)

2. 重构getData函数为Fetch实现

替换原有的getPostsByTag调用,改用Fetch请求并配置缓存策略:

async function getData(name: string) {
  // 替换为你的Firebase项目ID和集合名
  const PROJECT_ID = "your-firebase-project-id";
  const COLLECTION_NAME = "posts";
  
  // 编码查询条件,避免URL转义问题
  const query = encodeURIComponent(`tag='${name}'`);
  const url = `https://firestore.googleapis.com/v1/projects/${PROJECT_ID}/databases/(default)/documents/${COLLECTION_NAME}?q=${query}`;

  // 发起Fetch请求,配置Next.js缓存规则
  const response = await fetch(url, {
    next: {
      // 可选:设置60秒后自动重新验证数据,适合定期更新的内容
      revalidate: 60,
      // 可选:静态缓存(默认行为,永久有效除非重新部署)
      // cache: 'force-cache'
      // 可选:禁用缓存,每次请求都拉取最新数据
      // cache: 'no-store'
    },
  });

  if (!response.ok) {
    throw new Error("获取Firestore数据失败");
  }

  // 解析Firestore返回的原始数据
  const firestoreData = await response.json();
  // 将Firestore的文档结构转换为业务所需格式
  const posts = firestoreData.documents?.map((doc: any) => ({
    id: doc.name.split("/").pop(), // 提取文档ID
    title: doc.fields.title.stringValue,
    tag: doc.fields.tag.stringValue,
    content: doc.fields.content.stringValue,
    // 根据你的实际字段类型补充其他属性,比如integerValue、booleanValue等
  })) || [];

  return { posts };
}

3. 关键细节说明

  • 缓存策略配置:Next.js通过next选项控制缓存:
    • revalidate: N:设置数据新鲜度,N秒后自动重新拉取最新数据
    • cache: 'force-cache':默认静态缓存,数据会被持久化到CDN,除非重新部署或主动刷新
    • cache: 'no-store':完全禁用缓存,每次请求都获取实时数据
  • Firestore数据转换:Firestore REST返回的字段值会按类型存储在stringValue、integerValue等属性中,需根据实际字段类型对应提取
  • 权限访问处理:如果你的Firestore数据需要权限验证,需在请求头中携带ID Token:
    headers: {
      Authorization: `Bearer ${你的ID Token}`
    }
    
    ID Token可通过Firebase Auth的客户端或服务端SDK获取

4. 原有组件逻辑保持不变

原Categorias组件无需修改,直接调用新的getData函数即可:

export default async function Categorias({ params }: { params: { name: string } }) {
  const receiver = await getData(params.name);
  const posts = receiver.posts;
  return (
    <>
      <BarTop value={100} />
      <CategoryData name={params.name} postsData={posts} />
    </>
  );
}

内容的提问来源于stack exchange,提问作者Pife Mena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:15:20