# Nuxt Users Module Nuxt Users is a comprehensive authentication and user management module for Nuxt 3 and Nuxt 4 applications. It provides a complete, production-ready solution with zero-configuration setup, supporting multiple databases (SQLite, MySQL, PostgreSQL), secure password handling with bcrypt, role-based access control, password reset functionality, and pre-built Vue components. The module is designed with security-first principles, featuring a whitelist-based authorization system and automatic session management. The module integrates seamlessly into Nuxt applications through a single module registration, automatically setting up API endpoints, database tables, authentication middleware, and client-side composables. It includes a powerful CLI for database operations, user creation, and migrations. With TypeScript support throughout and extensive customization options, it scales from simple authentication needs to complex multi-tenant applications while maintaining developer-friendly defaults. ## Installation and Basic Setup ### Zero-Config Installation Install the module and required dependencies, then add to your Nuxt configuration for immediate use with SQLite database. ```bash # Install module and dependencies npm install nuxt-users db0 better-sqlite3 bcrypt nodemailer # Initialize database npx nuxt-users migrate # Create admin user npx nuxt-users create-user -e admin@example.com -n "Admin User" -p password123 -r admin ``` ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-users'], nuxtUsers: { auth: { permissions: { admin: ['*'], // Admin can access everything user: ['/profile', '/dashboard', '/api/nuxt-users/me'] } } } }) ``` ### Production Configuration with MySQL Configure for production with MySQL database, custom email provider, and environment variables. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-users'], runtimeConfig: { nuxtUsers: { connector: { name: 'mysql', options: { host: process.env.NUXT_NUXT_USERS_CONNECTOR_OPTIONS_HOST || 'localhost', port: 3306, user: undefined, // Use NUXT_NUXT_USERS_CONNECTOR_OPTIONS_USER env var password: undefined, // Use NUXT_NUXT_USERS_CONNECTOR_OPTIONS_PASSWORD database: undefined // Use NUXT_NUXT_USERS_CONNECTOR_OPTIONS_DATABASE } }, mailer: { host: process.env.NUXT_NUXT_USERS_MAILER_HOST || 'smtp.gmail.com', port: 587, secure: false, auth: { user: undefined, // Use NUXT_NUXT_USERS_MAILER_AUTH_USER pass: undefined // Use NUXT_NUXT_USERS_MAILER_AUTH_PASS }, defaults: { from: '"My App" ' } }, auth: { tokenExpiration: 1440, // 24 hours rememberMeExpiration: 30, // 30 days whitelist: ['/register', '/about', '/public'], permissions: { admin: ['*'], manager: [ { path: '/api/nuxt-users/*', methods: ['GET', 'PATCH'] }, '/admin/dashboard', '/reports' ], user: ['/profile', '/settings', '/api/nuxt-users/me'] } }, passwordValidation: { minLength: 10, requireUppercase: true, requireLowercase: true, requireNumbers: true, requireSpecialChars: true, preventCommonPasswords: true } } } }) ``` ```bash # .env NUXT_NUXT_USERS_CONNECTOR_OPTIONS_HOST=prod-db.example.com NUXT_NUXT_USERS_CONNECTOR_OPTIONS_USER=app_user NUXT_NUXT_USERS_CONNECTOR_OPTIONS_PASSWORD=secure_password_here NUXT_NUXT_USERS_CONNECTOR_OPTIONS_DATABASE=production_db NUXT_NUXT_USERS_MAILER_HOST=smtp.sendgrid.net NUXT_NUXT_USERS_MAILER_AUTH_USER=apikey NUXT_NUXT_USERS_MAILER_AUTH_PASS=SG.xxxxxxxxxxxxxxxxxxxxx ``` ## User Authentication with useAuthentication ### Login with Remember Me Handle user login with optional persistent sessions across browser restarts. ```vue ``` ### Logout and Session Management Implement logout with confirmation and automatic cleanup of local storage. ```vue ``` ### Automatic Session Restoration Restore user session on app startup with server-side validation. ```vue ``` ## User Registration API ### POST /api/nuxt-users/register Register a new user with email confirmation workflow. ```bash curl -X POST http://localhost:3000/api/nuxt-users/register \ -H "Content-Type: application/json" \ -d '{ "email": "newuser@example.com", "name": "John Doe", "password": "SecurePass123!" }' ``` ```json { "user": { "id": 1, "email": "newuser@example.com", "name": "John Doe", "role": "user", "active": false, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T00:00:00.000Z" }, "message": "Registration successful! Please check your email to confirm your account." } ``` ```vue ``` ### GET /api/nuxt-users/confirm-email Confirm user email address and activate account. ```bash curl "http://localhost:3000/api/nuxt-users/confirm-email?token=abc123def456&email=newuser@example.com" ``` ```json { "success": true, "message": "Email confirmed successfully! Your account is now active. You can now log in." } ``` ```vue ``` ## User Session API ### POST /api/nuxt-users/session Authenticate user and create session. ```bash curl -X POST http://localhost:3000/api/nuxt-users/session \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com", "password": "password123" }' ``` ```json { "user": { "id": 1, "email": "user@example.com", "name": "John Doe", "role": "user", "active": true, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T00:00:00.000Z" } } ``` ### DELETE /api/nuxt-users/session Logout current user and invalidate session. ```bash curl -X DELETE http://localhost:3000/api/nuxt-users/session \ -H "Cookie: nuxt-users-auth-token=your_token_here" ``` ```json { "message": "Logged out successfully" } ``` ## User Management API ### GET /api/nuxt-users Get paginated list of all users (admin only). ```bash curl "http://localhost:3000/api/nuxt-users?page=1&limit=10" \ -H "Cookie: nuxt-users-auth-token=admin_token" ``` ```json { "users": [ { "id": 1, "email": "admin@example.com", "name": "Admin User", "role": "admin", "active": true, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T00:00:00.000Z" } ], "pagination": { "page": 1, "limit": 10, "total": 1, "totalPages": 1, "hasNext": false, "hasPrev": false } } ``` ```vue ``` ### POST /api/nuxt-users Create new user (admin only). ```bash curl -X POST http://localhost:3000/api/nuxt-users \ -H "Content-Type: application/json" \ -H "Cookie: nuxt-users-auth-token=admin_token" \ -d '{ "email": "newuser@example.com", "name": "New User", "password": "SecurePass123!", "role": "user" }' ``` ```json { "user": { "id": 2, "email": "newuser@example.com", "name": "New User", "role": "user", "active": true, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T00:00:00.000Z" } } ``` ### GET /api/nuxt-users/:id Get user by ID (own profile or admin). ```bash curl http://localhost:3000/api/nuxt-users/1 \ -H "Cookie: nuxt-users-auth-token=user_token" ``` ```json { "user": { "id": 1, "email": "user@example.com", "name": "John Doe", "role": "user", "active": true, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T00:00:00.000Z" } } ``` ### PATCH /api/nuxt-users/:id Update user information (own profile or admin). ```bash curl -X PATCH http://localhost:3000/api/nuxt-users/1 \ -H "Content-Type: application/json" \ -H "Cookie: nuxt-users-auth-token=admin_token" \ -d '{ "name": "Updated Name", "role": "manager", "active": true }' ``` ```json { "user": { "id": 1, "email": "user@example.com", "name": "Updated Name", "role": "manager", "active": true, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T12:30:00.000Z" } } ``` ### DELETE /api/nuxt-users/:id Delete user (admin only). ```bash curl -X DELETE http://localhost:3000/api/nuxt-users/2 \ -H "Cookie: nuxt-users-auth-token=admin_token" ``` ```json { "success": true } ``` ```vue ``` ## Current User Profile API ### GET /api/nuxt-users/me Get current authenticated user profile. ```bash curl http://localhost:3000/api/nuxt-users/me \ -H "Cookie: nuxt-users-auth-token=user_token" ``` ```json { "user": { "id": 1, "email": "user@example.com", "name": "John Doe", "role": "user", "active": true, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T00:00:00.000Z" } } ``` ```vue ``` ### PATCH /api/nuxt-users/me Update current user profile. ```bash curl -X PATCH http://localhost:3000/api/nuxt-users/me \ -H "Content-Type: application/json" \ -H "Cookie: nuxt-users-auth-token=user_token" \ -d '{ "name": "Johnathan Doe", "email": "john.doe@newemail.com" }' ``` ```json { "user": { "id": 1, "email": "john.doe@newemail.com", "name": "Johnathan Doe", "role": "user", "active": true, "created_at": "2024-01-01T00:00:00.000Z", "updated_at": "2024-01-01T13:45:00.000Z" } } ``` ### PATCH /api/nuxt-users/password Update current user password. ```bash curl -X PATCH http://localhost:3000/api/nuxt-users/password \ -H "Content-Type: application/json" \ -H "Cookie: nuxt-users-auth-token=user_token" \ -d '{ "currentPassword": "oldPassword123", "newPassword": "NewSecurePass456!", "newPasswordConfirmation": "NewSecurePass456!" }' ``` ```json { "message": "Password updated successfully" } ``` ```vue ``` ## Password Reset API ### POST /api/nuxt-users/password/forgot Request password reset email. ```bash curl -X POST http://localhost:3000/api/nuxt-users/password/forgot \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com" }' ``` ```json { "message": "If a user with that email exists, a password reset link has been sent." } ``` ```vue ``` ### POST /api/nuxt-users/password/reset Reset password with token. ```bash curl -X POST http://localhost:3000/api/nuxt-users/password/reset \ -H "Content-Type: application/json" \ -d '{ "token": "reset-token-from-email", "email": "user@example.com", "password": "NewSecurePass123!", "password_confirmation": "NewSecurePass123!" }' ``` ```json { "message": "Password has been reset successfully. You can now log in with your new password." } ``` ```vue ``` ## Password Validation with usePasswordValidation ### Real-time Password Strength Indicator Validate passwords against configured rules with real-time feedback. ```vue ``` ### Custom Password Validation Rules Override default validation rules for specific use cases. ```vue ``` ## Role-Based Authorization with usePublicPaths ### Check Route Access Permissions Verify if current user can access specific routes based on their role. ```vue ``` ### Conditional Component Rendering Show/hide UI elements based on user permissions. ```vue ``` ## CLI Commands ### Database Migration Initialize or update database schema with all required tables. ```bash # Run all pending migrations npx nuxt-users migrate # Typical output: # ✓ Connected to database # ✓ Migrations table exists # ✓ Running migration: create_users_table # ✓ Running migration: create_personal_access_tokens_table # ✓ Running migration: create_password_reset_tokens_table # ✓ All migrations completed successfully ``` ### User Management Commands Create, modify, and manage users via command line. ```bash # Create admin user npx nuxt-users create-user \ -e admin@example.com \ -n "Admin User" \ -p SecurePassword123! \ -r admin # Create regular user npx nuxt-users create-user \ -e user@example.com \ -n "Regular User" \ -p userpass123 \ -r user # Create user with short flags npx nuxt-users create-user -e dev@example.com -n "Dev User" -p dev123 -r user ``` ### Manual Table Creation Create individual database tables when needed. ```bash # Create users table npx nuxt-users create-users-table # Create personal access tokens table npx nuxt-users create-personal-access-tokens-table # Create password reset tokens table npx nuxt-users create-password-reset-tokens-table # Create migrations tracking table npx nuxt-users create-migrations-table ``` ### Database Schema Modifications Add new columns to existing tables for feature updates. ```bash # Add 'active' column to users table (for account activation) npx nuxt-users add-active-to-users # Add Google OAuth fields to users table npx nuxt-users add-google-oauth-fields # These commands are idempotent - safe to run multiple times ``` ### Project Information Display current configuration and database status. ```bash # Show project info npx nuxt-users project-info # Output example: # Nuxt Users Module - Project Information # # Database Configuration: # Type: mysql # Host: localhost # Database: myapp_production # Tables: users, personal_access_tokens, password_reset_tokens # # Authentication: # Token Expiration: 1440 minutes (24 hours) # Remember Me: 30 days # # Password Policy: # Minimum Length: 8 # Require Uppercase: true # Require Numbers: true ``` ## Pre-built Vue Components ### NUsersLoginForm Component Complete login form with forgot password link and validation. ```vue ``` ### NUsersRegisterForm Component Registration form with password strength indicator and email confirmation. ```vue ``` ### NUsersResetPasswordForm Component Password reset form that reads token from URL query parameters. ```vue ``` ### NUsersLogoutLink Component Simple logout link with automatic session cleanup. ```vue ``` ### NUsersList Component Admin component for user management with pagination. ```vue ``` The Nuxt Users module provides a complete authentication and authorization system suitable for projects ranging from simple blogs to complex multi-tenant applications. Its primary use cases include adding user authentication to existing Nuxt applications, building admin dashboards with role-based access control, implementing customer portals with self-service password reset, and creating SaaS applications with team member management. The module's zero-config approach makes it ideal for rapid prototyping while its extensive configuration options support production deployments at scale. Integration patterns typically involve adding the module to an existing Nuxt project, configuring role-based permissions in nuxt.config.ts, using the provided composables (useAuthentication, useUsers) for programmatic access, and leveraging pre-built components for UI implementation. The module integrates seamlessly with Nuxt's server middleware for API route protection, supports SSR and client-side rendering, and can be combined with other Nuxt modules like nuxt-api-shield for enhanced security. Advanced patterns include custom email templates via the mailer configuration, OAuth integration with Google authentication, and multi-database deployments using environment-specific configurations with the runtime config pattern.