NextAuth / Auth.js 数据库 Schema 详解:四张表怎么协作
NextAuth(现名 Auth.js)在你的数据库里建 4 张表:users、accounts、sessions、verification_tokens。users 与 accounts 通过 accounts.user_id 一对一关联;sessions 通过 sessions.user_id 关联用户;verification_tokens 短生命周期、自动清理。
四张表
users
| 列 | 类型 | 含义 |
|---|---|---|
| id | text/UUID | 主键,NextAuth 生成 |
| name | text | 来自 OAuth 提供方(Google/GitHub 等)的显示名 |
| text | 用户邮箱;提供方不分享则为 null | |
| email_verified | timestamp | 邮箱验证时间;未验证为 null |
| image | text | 提供方头像 URL |
| created_at | timestamp | 首次登录时间 |
| updated_at | timestamp | 上次从提供方同步资料 |
accounts:把用户关联到 OAuth 提供方,一个用户可多个账号(Google + GitHub)。
| 列 | 类型 | 含义 |
|---|---|---|
| id | text/UUID | 主键 |
| user_id | text | 外键 → users.id |
| type | text | 恒为 "oauth" 或 "oidc" |
| provider | text | "google"、"github"、"discord" 等 |
| provider_account_id | text | 提供方给该用户的唯一 ID |
| refresh_token | text | OAuth refresh token(生产环境加密) |
| access_token | text | OAuth access token(生产环境加密) |
| expires_at | integer | access token 过期时间(Unix 时间戳) |
| token_type | text | 通常 "Bearer" |
| scope | text | 提供方授予的权限 |
sessions 记录登录会话,verification_tokens 用于邮箱验证/密码重置的一次性码(哈希存储、过期自动失效)。
实践建议
- 自建 schema 时严格按这四张表的关系建外键,别把 token 明文落库(生产要加密);
- verification_tokens 靠过期时间自清理,别忘了索引过期列;
- 多提供方登录时 accounts 是核心关联表,user_id 外键不要设错方向。
来源:NextAuth / Auth.js Database Schema Explained - DEV Community