Skip to content

Database Internals ​

This guide covers the internal database utilities and functions used by the Nuxt Users module. These utilities are primarily intended for module contributors and advanced developers who need to extend the module's functionality or integrate with its database layer.

Core Database Utilities ​

useNuxtUsersDatabase() ​

The primary server-side utility for accessing the module's database connection. This provides access to the same database instance used by the module for user authentication, tokens, and other core functionality.

typescript
import { useNuxtUsersDatabase } from '#nuxt-users/server'

export default defineEventHandler(async (event) => {
  const { database, options } = await useNuxtUsersDatabase()
  
  // Access the database instance
  const users = await database.sql`SELECT * FROM ${options.tables.users}`
  
  return users
})

Returns:

  • database: The db0 database instance
  • options: Module configuration including table names and connector settings

Important Notes:

  • This is a server-side only utility and should not be used in client-side code
  • The database instance uses the same connection and configuration as the module
  • Available in API routes, server middleware, and other server-side contexts

useDb(options) ​

Lower-level database utility that creates a database connection based on the provided options. This is used internally by useNuxtUsersDatabase() and other database utilities.

typescript
import { useDb } from '#nuxt-users/server'
import type { ModuleOptions } from '#nuxt-users/types'

const options: ModuleOptions = {
  connector: {
    name: 'sqlite',
    options: { path: './data/users.sqlite3' }
  },
  tables: {
    users: 'users',
    personalAccessTokens: 'personal_access_tokens',
    passwordResetTokens: 'password_reset_tokens'
  }
}

const db = await useDb(options)
const result = await db.sql`SELECT * FROM users`

Parameters:

  • options: ModuleOptions containing connector and table configuration

Returns:

  • Database instance created with db0

getConnector(name) ​

Dynamically imports and returns the appropriate database connector based on the connector name.

typescript
import { getConnector } from '#nuxt-users/server'

const connector = await getConnector('sqlite')
// Returns the better-sqlite3 connector

const mysqlConnector = await getConnector('mysql')
// Returns the mysql2 connector

const pgConnector = await getConnector('postgresql')
// Returns the postgresql connector

Supported Connectors:

  • sqlite: Uses better-sqlite3
  • mysql: Uses mysql2
  • postgresql: Uses pg

Error Handling:

  • Throws descriptive errors if the connector package is not installed
  • Provides installation instructions for missing peer dependencies

checkTableExists(options, tableName) ​

Utility function to check if a specific table exists in the database.

typescript
import { checkTableExists } from '#nuxt-users/server'

const exists = await checkTableExists(options, 'users')
if (!exists) {
  console.log('Users table does not exist')
}

Parameters:

  • options: ModuleOptions containing database configuration
  • tableName: Name of the table to check

Returns:

  • boolean: True if table exists, false otherwise

Migration System ​

runMigrations(options) ​

Executes all pending database migrations. This is the main entry point for the migration system.

typescript
import { runMigrations } from '#nuxt-users/server'

await runMigrations(options)

It returns the names of the migrations applied by this run, and throws on the first failure.

Migration Process:

  1. Ensures migrations table exists
  2. Checks which migrations have been applied
  3. Runs pending migrations in order. For each one, the DDL, a check that the resulting table, column or index really exists, and the row in the migrations table form one unit: the migration is recorded only if its schema change is in place
  4. Stops at the first failure. The failed migration is not recorded, so it runs again next time

Atomicity per database:

  • SQLite: each migration runs in a BEGIN IMMEDIATE transaction, so a locked database fails before any DDL runs. While another connection holds the write lock, the migration waits with async retries (up to 30 seconds) instead of better-sqlite3's synchronous busy wait, which would block the event loop. If a transaction is already open on the module's own connection (for example an app migration run through useNuxtUsersDatabase()), it waits for that transaction to end instead of running inside it
  • PostgreSQL: each migration runs in a transaction, with an advisory lock that serializes concurrent runs from several instances
  • MySQL: DDL commits implicitly, so there is no transaction. The existence check still keeps a failed migration from being recorded

Built-in Migrations:

  • create_migrations_table: Creates the migrations tracking table
  • create_users_table: Creates the users table
  • create_personal_access_tokens_table: Creates the tokens table
  • create_password_reset_tokens_table: Creates the password reset tokens table
  • add_active_to_users: Adds the active column to users table
  • add_google_oauth_fields: Adds the google_id and profile_picture columns, if missing
  • add_active_index_to_users: Adds an index on users.active
  • add_tokenable_index_to_personal_access_tokens: Adds an index on the token owner columns
  • create_passkey_tables: Creates the passkeys and passkey_challenges tables used by passkey login
  • add_user_handle_to_passkey_challenges: Adds user_handle to passkey_challenges, so a passkey is saved with the WebAuthn user handle its registration sent to the authenticator
  • add_purpose_to_password_reset_tokens: Adds purpose to password_reset_tokens, so a password reset token can never confirm an email. Existing tokens of inactive users become confirmation tokens, the rest password reset tokens

getAppliedMigrations(options) ​

Returns a list of migrations that have already been applied to the database.

typescript
import { getAppliedMigrations } from '#nuxt-users/server'

const applied = await getAppliedMigrations(options)
console.log('Applied migrations:', applied)
// Output: ['create_migrations_table', 'create_users_table', ...]

Auto-Migration on Startup ​

The module automatically runs database migrations on server startup via a Nitro plugin. This ensures the database schema is always up-to-date without manual intervention.

How it works:

  • The auto-migrate plugin runs as a Nitro app plugin
  • On every server start, it checks for pending migrations
  • Applied migrations are tracked in the migrations table
  • Only new migrations are executed

Behavior:

  • If migrations fail, an error is logged to the console
  • The server continues running even if migrations fail (for development convenience). Nothing is recorded for the failed migration, so it runs again on the next start
  • When the run finishes, the Nitro runtime hook nuxt-users:migrated is called

Running app migrations after nuxt-users' migrations:

Nitro does not wait for async plugins, so an app plugin that migrates the same database at startup runs at the same time as nuxt-users' migrations. Wait for the nuxt-users:migrated hook instead:

ts
// server/plugins/migrate.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('nuxt-users:migrated', async ({ applied, error }) => {
    if (error) {
      console.error('nuxt-users migrations failed, skipping app migrations')
      return
    }
    console.log('nuxt-users applied:', applied)
    await runMyAppMigrations()
  })
})

The payload is { applied: string[], error?: unknown } (type NuxtUsersMigratedContext from nuxt-users/utils). The hook is called on every start, also when there was nothing to migrate.

Disabling Auto-Migration:

Set autoMigrate: false to run the migrations yourself, for example with npx nuxt-users migrate before the app starts. The nuxt-users:migrated hook is then not called.

ts
// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxt-users'],
  nuxtUsers: {
    autoMigrate: false
  }
})

It can also be set at runtime with NUXT_NUXT_USERS_AUTO_MIGRATE=false.

Manual Migration Control:

For production deployments, you may want to run migrations manually:

bash
# Run from your Nuxt project root (where nuxt.config lives)
npx nuxt-users migrate

If you run this on a production server after build-only deploys, read Using nuxt-users CLI in Production.

Or programmatically:

typescript
// In your own server plugin
import { runMigrations } from '#nuxt-users/server'

export default defineNitroPlugin(async (nitroApp) => {
  const config = useRuntimeConfig()
  await runMigrations(config.nuxtUsers)
})

Migration Table:

The auto-migration system creates a migrations table to track applied migrations:

ColumnTypeDescription
idINTEGERAuto-increment primary key
nameVARCHAR(255)Migration name
executed_atDATETIMEWhen the migration was applied

markMigrationAsApplied(options, migrationName) ​

Marks a specific migration as applied in the migrations table.

typescript
import { markMigrationAsApplied } from '#nuxt-users/server'

await markMigrationAsApplied(options, 'my_custom_migration')

Table Creation Utilities ​

createUsersTable(options) ​

Creates the users table with the appropriate schema for the configured database connector.

typescript
import { createUsersTable } from '#nuxt-users/server'

await createUsersTable(options)

Table Schema:

  • id: Primary key (auto-increment)
  • email: Unique email address
  • name: User's display name
  • password: Hashed password
  • role: User role (default: 'user')
  • created_at: Creation timestamp
  • updated_at: Last update timestamp
  • active: User active status (added by migration)

createPersonalAccessTokensTable(options) ​

Creates the personal access tokens table for authentication tokens.

typescript
import { createPersonalAccessTokensTable } from '#nuxt-users/server'

await createPersonalAccessTokensTable(options)

createPasswordResetTokensTable(options) ​

Creates the table for email tokens: password reset tokens and email confirmation tokens. Each row has a purpose (password_reset or email_confirmation), and a token is only accepted for its own purpose. Tokens are stored as SHA-256 hashes; see ADR 0001 for why.

typescript
import { createPasswordResetTokensTable } from '#nuxt-users/server'

await createPasswordResetTokensTable(options)

createMigrationsTable(options) ​

Creates the migrations tracking table used by the migration system.

typescript
import { createMigrationsTable } from '#nuxt-users/server'

await createMigrationsTable(options)

User Management Utilities ​

createUser(userData, options) ​

Creates a new user in the database with password hashing and validation.

typescript
import { createUser } from '#nuxt-users/server'

const user = await createUser({
  email: '[email protected]',
  name: 'John Doe',
  password: 'securePassword123',
  role: 'admin',
  active: true
}, options)

Features:

  • Automatic password hashing with bcrypt
  • Password strength validation
  • Returns user data without password
  • Handles database-specific timestamp formatting

findUserByEmail(email, options) ​

Finds a user by their email address.

typescript
import { findUserByEmail } from '#nuxt-users/server'

const user = await findUserByEmail('[email protected]', options)
if (user) {
  console.log('User found:', user.name)
}

findUserById(id, options, withPass?) ​

Finds a user by their ID with optional password inclusion.

typescript
import { findUserById } from '#nuxt-users/server'

// Without password (default)
const user = await findUserById(1, options)

// With password
const userWithPassword = await findUserById(1, options, true)

updateUser(id, userData, options) ​

Updates user information with security safeguards.

typescript
import { updateUser } from '#nuxt-users/server'

const updatedUser = await updateUser(1, {
  name: 'New Name',
  role: 'admin',
  active: false
}, options)

Security Features:

  • Only allows updating specific fields (name, email, role, active)
  • Automatically revokes tokens when user is deactivated
  • Prevents mass-assignment vulnerabilities

updateUserPassword(email, newPassword, options) ​

Updates a user's password with validation and hashing.

typescript
import { updateUserPassword } from '#nuxt-users/server'

await updateUserPassword('[email protected]', 'newSecurePassword', options)

deleteUser(id, options) ​

Deletes a user from the database.

typescript
import { deleteUser } from '#nuxt-users/server'

await deleteUser(1, options)

Token Management Utilities ​

getCurrentUserFromToken(token, options, withPass?) ​

Retrieves user information from an authentication token.

typescript
import { getCurrentUserFromToken } from '#nuxt-users/server'

const user = await getCurrentUserFromToken('auth-token', options)
if (user) {
  console.log('Authenticated user:', user.name)
}

Features:

  • Validates token expiration
  • Updates last_used_at timestamp
  • Checks user active status
  • Optional password inclusion

cleanupPersonalAccessTokens(options, includeNoExpiration?) ​

Comprehensive token cleanup utility.

typescript
import { cleanupPersonalAccessTokens } from '#nuxt-users/server'

const result = await cleanupPersonalAccessTokens(options, true)
console.log(`Cleaned up ${result.totalCount} tokens`)

Returns:

  • expiredCount: Number of expired tokens removed
  • noExpirationCount: Number of tokens without expiration removed
  • totalCount: Total tokens removed

revokeUserTokens(userId, options) ​

Revokes all tokens for a specific user.

typescript
import { revokeUserTokens } from '#nuxt-users/server'

await revokeUserTokens(1, options)

getLastLoginTime(userId, options) ​

Gets the last login time for a user based on their most recent token creation. For many users at once, getLastLoginTimes(userIds, options) returns a Map of user id to last login (or null) in a single query.

typescript
import { getLastLoginTime } from '#nuxt-users/server'

const lastLogin = await getLastLoginTime(1, options)
if (lastLogin) {
  console.log('Last login:', new Date(lastLogin))
}

Utility Functions ​

hasAnyUsers(options) ​

Checks if any users exist in the database.

typescript
import { hasAnyUsers } from '#nuxt-users/server'

const usersExist = await hasAnyUsers(options)
if (!usersExist) {
  console.log('No users found - first time setup')
}

Database Connector Support ​

The module supports three database connectors with automatic schema adaptation:

SQLite (better-sqlite3) ​

  • File-based database
  • Ideal for development and small applications
  • Uses INTEGER PRIMARY KEY AUTOINCREMENT
  • Supports DATETIME for timestamps

MySQL (mysql2) ​

  • Full-featured MySQL support
  • Uses INT AUTO_INCREMENT PRIMARY KEY
  • Supports VARCHAR with length specifications
  • Uses DATETIME for timestamps

PostgreSQL (pg) ​

  • Enterprise-grade PostgreSQL support
  • Uses SERIAL PRIMARY KEY
  • Supports VARCHAR with length specifications
  • Uses TIMESTAMPTZ for timezone-aware timestamps

Error Handling ​

The database utilities include comprehensive error handling:

  • Connection Errors: Descriptive messages for database connection failures
  • Missing Dependencies: Clear instructions for installing required peer dependencies (bcrypt, database drivers, nodemailer)
  • Migration Failures: Detailed error reporting with rollback capabilities
  • Validation Errors: Password and data validation with specific error messages
  • Table Existence: Graceful handling of missing tables

Best Practices ​

For Module Contributors ​

  1. Always use transactions for multi-step operations
  2. Validate input data before database operations
  3. Handle database-specific differences in SQL queries
  4. Use parameterized queries to prevent SQL injection
  5. Test with all supported database connectors

For Advanced Users ​

  1. Use useNuxtUsersDatabase() instead of direct database access
  2. Respect the module's table structure when extending functionality
  3. Follow the migration pattern for schema changes
  4. Handle errors gracefully in production environments
  5. Monitor token cleanup for performance optimization

Integration Examples ​

Custom API Route with Database Access ​

typescript
// server/api/admin/users.get.ts
export default defineEventHandler(async (event) => {
  const { database, options } = await useNuxtUsersDatabase()
  
  // Get all active users with their last login
  const users = await database.sql`
    SELECT u.*, 
           (SELECT MAX(created_at) 
            FROM ${options.tables.personalAccessTokens} 
            WHERE tokenable_id = u.id) as last_login
    FROM ${options.tables.users} u
    WHERE u.active = true
    ORDER BY u.created_at DESC
  `
  
  return users.rows
})

Custom Migration ​

typescript
// Custom migration function
const addCustomFieldToUsers = async (options: ModuleOptions) => {
  const db = await useDb(options)
  const tableName = options.tables.users
  
  await db.sql`ALTER TABLE ${tableName} ADD COLUMN custom_field TEXT`
}

// Add to migrations array
const customMigrations = [
  {
    name: 'add_custom_field_to_users',
    run: addCustomFieldToUsers
  }
]

This documentation provides comprehensive coverage of the internal database utilities while maintaining focus on developer and contributor needs. The utilities are powerful tools for extending the module's functionality and integrating with existing database systems.

Released under the MIT License.