nuxt-users

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Nuxt Users skill

Nuxt Users 技能

Initial setup

初始设置

  1. Install the module and peer dependencies
    bash
    npm install nuxt-users
    npm install db0 better-sqlite3 bcrypt nodemailer
    For MySQL or PostgreSQL, install the corresponding driver (
    mysql2
    or
    pg
    ) instead of or in addition to
    better-sqlite3
    as required.
  2. Register the module in
    nuxt.config.ts
    ts
    export default defineNuxtConfig({
      modules: ['nuxt-users']
    })
  3. Run migrations From the project root (where
    nuxt.config.ts
    lives):
    bash
    npx nuxt-users migrate
  4. Create at least one user
    bash
    npx nuxt-users create-user -e admin@example.com -n "Admin User" -p password123 -r admin
    Flags:
    -e
    email,
    -n
    name,
    -p
    password,
    -r
    role (optional).
  5. Configure permissions
    ts
    export default defineNuxtConfig({
      modules: ['nuxt-users'],
      nuxtUsers: {
        auth: {
          permissions: {
            admin: ['*'],
            user: ['/profile', '/api/nuxt-users/me']
          }
        }
      }
    })
  6. Use login in a page
    • Use the
      NUsersLoginForm
      component and handle
      @success
      by calling
      login(user)
      from
      useAuthentication()
      .
    • Optionally redirect after login (e.g.
      navigateTo('/')
      ).
  1. 安装模块及 peer dependencies
    bash
    npm install nuxt-users
    npm install db0 better-sqlite3 bcrypt nodemailer
    对于 MySQL 或 PostgreSQL,请根据需要替代或同时安装
    better-sqlite3
    ,并安装相应的驱动(
    mysql2
    或
    pg
    )。
  2. 在
    nuxt.config.ts
    中注册模块
    ts
    export default defineNuxtConfig({
      modules: ['nuxt-users']
    })
  3. 运行数据库迁移 在项目根目录(
    nuxt.config.ts
    所在位置)运行:
    bash
    npx nuxt-users migrate
  4. 至少创建一个用户
    bash
    npx nuxt-users create-user -e admin@example.com -n "Admin User" -p password123 -r admin
    参数:
    -e
    邮箱、
    -n
    姓名、
    -p
    密码、
    -r
    角色(可选)。
  5. 配置权限
    ts
    export default defineNuxtConfig({
      modules: ['nuxt-users'],
      nuxtUsers: {
        auth: {
          permissions: {
            admin: ['*'],
            user: ['/profile', '/api/nuxt-users/me']
          }
        }
      }
    })
  6. 在页面中使用登录功能
    • 使用
      NUsersLoginForm
      组件,并通过调用
      useAuthentication()
      中的
      login(user)
      处理
      @success
      。
    • 可选择在登录后进行重定向(例如
      navigateTo('/')
      )。

Configuration reference (nuxt.config.ts)

配置参考(nuxt.config.ts)

All options live under
nuxtUsers
in
nuxt.config.ts
.
AreaKeyNotes
Database
connector.name
'sqlite' | 'mysql' | 'postgresql'
Database
connector.options
path
(SQLite), or
host
,
port
,
user
,
password
,
database
(MySQL/PostgreSQL)
API
apiBasePath
Default
'/api/nuxt-users'
Tables
tables.users
,
tables.personalAccessTokens
,
tables.passwordResetTokens
,
tables.migrations
Custom table names
Mailer
mailer
Nodemailer config for password reset emails
URLs
passwordResetUrl
,
emailConfirmationUrl
Paths for redirects
Auth
auth.whitelist
Public routes (e.g.
['/register']
);
/login
is always public
Auth
auth.tokenExpiration
Minutes (default 1440)
Auth
auth.rememberMeExpiration
Days (default 30)
Auth
auth.permissions
Role → paths (e.g.
admin: ['*']
,
user: ['/profile']
). Keys are the predefined roles.
Auth
auth.allowCustomRoles
Default
false
. When
true
, create/update APIs and
NUsersUserForm
accept roles not listed in
permissions
. Empty
permissions
(bootstrap) already accepts any role.
Auth
auth.google
Google OAuth:
clientId
,
clientSecret
,
callbackUrl
, etc.
Password
passwordValidation
minLength
,
requireUppercase
,
requireLowercase
,
requireNumbers
,
requireSpecialChars
,
preventCommonPasswords
Data
hardDelete
true
= hard delete,
false
= soft delete (default)
Locale
locale.default
,
locale.texts
,
locale.fallbackLocale
Localization
Runtime config is also supported: use
runtimeConfig.nuxtUsers
for env-based or server-only settings.
所有选项都位于
nuxt.config.ts
的
nuxtUsers
下。
领域键说明
数据库
connector.name
'sqlite' | 'mysql' | 'postgresql'
数据库
connector.options
path
(SQLite),或
host
、
port
、
user
、
password
、
database
(MySQL/PostgreSQL)
API
apiBasePath
默认值为
'/api/nuxt-users'
表
tables.users
、
tables.personalAccessTokens
、
tables.passwordResetTokens
、
tables.migrations
自定义表名
邮件服务
mailer
用于密码重置邮件的 Nodemailer 配置
URL
passwordResetUrl
、
emailConfirmationUrl
用于重定向的路径
身份验证
auth.whitelist
公共路由(例如
['/register']
);
/login
始终为公共路由
身份验证
auth.tokenExpiration
分钟数(默认 1440)
身份验证
auth.rememberMeExpiration
天数(默认 30)
身份验证
auth.permissions
角色 → 路径(例如
admin: ['*']
、
user: ['/profile']
)。键为预定义角色。
身份验证
auth.allowCustomRoles
默认值为
false
。设为
true
时,创建/更新 API 和
NUsersUserForm
接受未在
permissions
中列出的角色。空的
permissions
(bootstrap)已经接受任何角色。
身份验证
auth.google
Google OAuth:
clientId
、
clientSecret
、
callbackUrl
等。
密码
passwordValidation
minLength
、
requireUppercase
、
requireLowercase
、
requireNumbers
、
requireSpecialChars
、
preventCommonPasswords
数据
hardDelete
true
= 硬删除,
false
= 软删除(默认)
本地化
locale.default
、
locale.texts
、
locale.fallbackLocale
本地化
也支持 runtime config:使用
runtimeConfig.nuxtUsers
进行基于环境变量或仅服务端的设置。

CLI commands

CLI 命令

Run from the project root so
nuxt.config.ts
(and optionally
.env
) are found.
  • Migrations
    bash
    npx nuxt-users migrate
  • Create user
    bash
    npx nuxt-users create-user -e <email> -n "<name>" -p <password> [-r <role>]
    Role should match a
    auth.permissions
    key unless
    auth.allowCustomRoles
    is
    true
    (or permissions are empty).
  • Legacy/table creation
    bash
    npx nuxt-users create-users-table
    npx nuxt-users create-personal-access-tokens-table
    npx nuxt-users create-password-reset-tokens-table
    npx nuxt-users create-migrations-table
Production: The CLI requires
nuxt-users
(and peers) installed where Node runs — it is not bundled inside
.output/
. Full config needs the app root with
nuxt.config
; build-only or
--omit=dev
deploys fall back to
DB_*
env vars. See
docs/user-guide/configuration.md
.
请从项目根目录运行,以便找到
nuxt.config.ts
(以及可选的
.env
)。
  • 数据库迁移
    bash
    npx nuxt-users migrate
  • 创建用户
    bash
    npx nuxt-users create-user -e <email> -n "<name>" -p <password> [-r <role>]
    除非
    auth.allowCustomRoles
    为
    true
    (或权限配置为空),否则角色应与
    auth.permissions
    的键匹配。
  • 旧版/表创建
    bash
    npx nuxt-users create-users-table
    npx nuxt-users create-personal-access-tokens-table
    npx nuxt-users create-password-reset-tokens-table
    npx nuxt-users create-migrations-table
生产环境: CLI 要求在 Node 运行的位置安装
nuxt-users
(及其 peer dependencies);它不会打包在
.output/
中。完整配置需要包含
nuxt.config
的应用根目录;仅构建或使用
--omit=dev
的部署会回退到
DB_*
环境变量。请参阅
docs/user-guide/configuration.md
。

Composables (auto-imported)

Composables(自动导入)

  • useAuthentication() —
    user
    ,
    isAuthenticated
    ,
    login(user, rememberMe?)
    ,
    logout()
    ,
    fetchUser(useSSR?)
    ,
    initializeUser()
  • useUsers() — Admin:
    users
    ,
    pagination
    ,
    loading
    ,
    error
    ,
    fetchUsers(page?, limit?)
    ,
    updateUser
    ,
    addUser
    ,
    removeUser(userId)
  • usePublicPaths() —
    getPublicPaths()
    ,
    getAccessiblePaths()
    ,
    isPublicPath(path)
    ,
    isAccessiblePath(path, method?)
  • usePasswordValidation(moduleOptions?, options?) —
    validate(password)
    ,
    isValid
    ,
    errors
    ,
    strength
    ,
    score
    ,
    clearValidation()
  • useNuxtUsersLocale() —
    t(key, params?)
    ,
    currentLocale
    ,
    fallbackLocale
  • useAuthentication() —
    user
    、
    isAuthenticated
    、
    login(user, rememberMe?)
    、
    logout()
    、
    fetchUser(useSSR?)
    、
    initializeUser()
  • useUsers() — 管理员:
    users
    、
    pagination
    、
    loading
    、
    error
    、
    fetchUsers(page?, limit?)
    、
    updateUser
    、
    addUser
    、
    removeUser(userId)
  • usePublicPaths() —
    getPublicPaths()
    、
    getAccessiblePaths()
    、
    isPublicPath(path)
    、
    isAccessiblePath(path, method?)
  • usePasswordValidation(moduleOptions?, options?) —
    validate(password)
    、
    isValid
    、
    errors
    、
    strength
    、
    score
    、
    clearValidation()
  • useNuxtUsersLocale() —
    t(key, params?)
    、
    currentLocale
    、
    fallbackLocale

Components

组件

  • NUsersLoginForm
    — Login form; use
    @success
    to call
    login(user)
    from
    useAuthentication()
  • NUsersLogoutLink
    — Logout link/button
  • NUsersProfileInfo
    — Display profile
  • NUsersResetPasswordForm
    — Password reset form
  • NUsersList
    — List users (admin)
  • NUsersUserForm
    — Create/edit user form; role select from
    auth.permissions
    keys; set
    auth.allowCustomRoles: true
    for a custom free-text role option
  • NUsersLoginForm
    — 登录表单;使用
    @success
    调用
    useAuthentication()
    中的
    login(user)
  • NUsersLogoutLink
    — 退出登录链接/按钮
  • NUsersProfileInfo
    — 显示个人资料
  • NUsersResetPasswordForm
    — 密码重置表单
  • NUsersList
    — 用户列表(管理员)
  • NUsersUserForm
    — 创建/编辑用户表单;角色选项来自
    auth.permissions
    的键;设置
    auth.allowCustomRoles: true
    可使用自定义自由文本角色选项

Troubleshooting

故障排除

SymptomFix
Redirected to login on protected routesSet
auth.permissions
so each role has access to needed routes
CLI config not found / wrong tablesRun CLI from the directory containing
nuxt.config
; see production note above
Migrations table missingRun
npx nuxt-users migrate
from project root
Database driver errorsInstall correct peer: SQLite →
better-sqlite3
, MySQL →
mysql2
, PostgreSQL →
pg
症状修复方法
在受保护的路由上被重定向到登录页设置
auth.permissions
,使每个角色都有权访问所需路由
找不到 CLI 配置或使用了错误的表在包含
nuxt.config
的目录中运行 CLI;请参阅上面的生产环境说明
缺少迁移表在项目根目录运行
npx nuxt-users migrate
数据库驱动错误安装正确的 peer dependency:SQLite →
better-sqlite3
,MySQL →
mysql2
,PostgreSQL →
pg

File references

文件参考

  • Project LLM context and config types: llms.txt in the repo root
  • Full docs: https://nuxt-users.webmania.cc/
  • Getting started and examples:
    ../../docs/user-guide/getting-started.md
    ,
    ../../docs/examples/basic-setup.md
  • Authorization:
    ../../docs/user-guide/authorization.md
  • Configuration details:
    ../../docs/user-guide/configuration.md
Keep
nuxtUsers
config and permissions in sync with the app’s roles and routes; use guard clauses and early returns when implementing custom auth logic.
  • 项目 LLM 上下文和配置类型:仓库根目录中的 llms.txt
  • 完整文档:https://nuxt-users.webmania.cc/
  • 入门和示例:
    ../../docs/user-guide/getting-started.md
    、
    ../../docs/examples/basic-setup.md
  • 授权:
    ../../docs/user-guide/authorization.md
  • 配置详情:
    ../../docs/user-guide/configuration.md
确保
nuxtUsers
配置和权限与应用的角色及路由保持同步;实现自定义身份验证逻辑时,使用 guard clauses 和 early return。