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

如何在Firebase中存储用户的自定义信息?

Firebase 存储用户自定义信息的可选方案

你可以根据业务需求选择以下三种主流实现方案:

  • 使用 Cloud Firestore / Realtime Database 存储用户专属文档(最推荐)
    这是绝大多数场景下的最优选择,支持存储任意结构、任意数量的用户自定义字段,天然支持跨设备同步,还可搭配安全规则做权限管控。
    注册成功后直接以用户uid为文档ID写入自定义数据即可,Web端示例代码如下:
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
import { getFirestore, doc, setDoc } from "firebase/firestore";

// 注册逻辑
const auth = getAuth();
const db = getFirestore();
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const user = userCredential.user;

// 写入用户自定义信息
await setDoc(doc(db, "users", user.uid), {
  favoriteColor: "blue", // 你需要的自定义字段
  email: user.email,
  registerTime: new Date()
});

后续需要读取时直接通过uid查询对应用户文档即可。

  • 使用 Firebase Auth 自定义声明
    该方案仅适合存储轻量化的权限类、标签类数据,单用户所有声明总大小不能超过1000字节,不建议存储业务类自定义信息。
    自定义声明需要通过Firebase Admin SDK在服务端写入,Node.js示例:
await admin.auth().setCustomUserClaims(uid, {
  favoriteColor: "blue"
});

前端可通过ID Token读取声明内容:

const idTokenResult = await auth.currentUser.getIdTokenResult();
const userFavoriteColor = idTokenResult.claims.favoriteColor;
  • 前端本地存储
    如果你不需要跨设备同步自定义信息,可以直接存在前端的localStorage或sessionStorage中,读写速度快无需调用后端接口,缺点是清除浏览器数据或更换设备后数据会丢失。
// 存储
localStorage.setItem("userFavoriteColor", "blue");
// 读取
const favoriteColor = localStorage.getItem("userFavoriteColor");

内容的提问来源于stack exchange,提问作者Sergio Bost

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 08:36:07