You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Firestore数据库中应使用Firebase UID还是Token作为用户文档引用?

Hey, great question—this is something a lot of developers grapple with when setting up Firestore alongside user authentication, so let’s break this down clearly.

UID vs Token ID for Firestore User Document IDs

This is actually the official Firebase recommended approach, and for good reason:

  • The UID is a permanent, unique identifier generated by Firebase Auth (whether you’re using email/password, social logins, or even custom auth). It never changes for a given user account—even if the user updates their email, display name, or other profile details.
  • Your database structure (Main/{uid}/... as you described) will be clean, intuitive, and align with common community patterns. Other developers working on your project will immediately understand how user data is organized.
  • Security rules become trivial to implement. You can easily restrict access so users only read/write their own data with rules like:
    match /Main/{uid}/{document=**} {
      allow read, write: if request.auth.uid == uid;
    }
    
  • There’s no extra overhead of mapping tokens to users—you can directly use the UID returned by Firebase Auth to fetch or modify the user’s document.

The only edge case to consider is if you allow users to fully delete their accounts and re-register with the same email later; in that case, the new account will get a new UID. But this is a behavior of the auth system itself, not a flaw in using UIDs as document IDs.

Token IDs (specifically ID Tokens) are short-lived, temporary credentials designed for identity verification, not as persistent user identifiers. Here’s why using them as document IDs is a bad idea:

  • ID Tokens expire (usually after 1 hour) and are refreshed regularly. This means the "identifier" for your user would change constantly, forcing you to either update the document ID repeatedly (which breaks any cross-collection references to that document) or maintain a messy mapping layer between tokens and actual user IDs.
  • A single user can have multiple valid ID Tokens at once (e.g., if they’re logged in on multiple devices). Using tokens as document IDs would lead to duplicate user documents, which is a nightmare for data consistency.
  • Security rules can’t reliably use token IDs for access control, since they’re transient and not tied to a stable user identity. You’d end up adding unnecessary complexity to your rules just to map tokens to UIDs anyway.

Final Verdict

In 99% of cases, using the UID as your Firestore user document reference is the correct, efficient, and best-practice choice. Token IDs should only be used in authentication flows (e.g., sending them to an API to verify a user’s current identity) and never as a permanent identifier in your database.

内容的提问来源于stack exchange,提问作者H Wong

火山引擎 最新活动