Troubleshooting

Troubleshooting User Registration

This guide helps you debug and fix common issues with the user registration functionality.

Quick Diagnostic Checklist

1. Check Environment Variables

# Verify your .env file has these required variables
cat .env | grep -E "NEXTAUTH_SECRET|NEXTAUTH_URL|MONGODB"

Required variables: .. code-block:: bash

NEXTAUTH_SECRET=<your-secret-key> # Must be set! NEXTAUTH_URL=http://localhost:3001 # Note: Server is on port 3001 MONGODB_URI=mongodb://localhost:27017 MONGODB_DATABASE=earthquake_catalogue

⚠️ IMPORTANT: The server is running on port 3001 (not 3000), so update NEXTAUTH_URL: .. code-block:: bash

NEXTAUTH_URL=http://localhost:3001

2. Run Database Migration

# Run the migration to set up authentication tables
npm run migrate:auth

Expected output: .. code-block:: text

🔐 Starting Authentication Schema Migration… ✓ Connected to MongoDB ✓ Created/Updated role: Administrator ✓ Created/Updated role: Editor ✓ Created/Updated role: Viewer ✓ Created/Updated role: Guest ✅ Authentication schema migration completed successfully!

3. Check MongoDB Connection

# Test MongoDB is running
mongosh --eval "db.version()"

# Or if using MongoDB Compass, connect to:
mongodb://localhost:27017

4. Browser Developer Tools Debugging

Open your browser’s Developer Tools (F12) and check:

Console Tab - Look for JavaScript errors:
Common errors:
- "Failed to fetch" → API endpoint not responding
- "NetworkError" → CORS or network issue
- "Unexpected token" → JSON parsing error
- "NEXTAUTH_SECRET" → Environment variable not set
Network Tab - Monitor the registration request:
  1. Open Network tab

  2. Click “Create account” button

  3. Look for POST /api/auth/register request

Successful response (201): .. code-block:: json

{

“message”: “User registered successfully”, “user”: {

“id”: “user_1234567890_abc123”, “email”: “test@example.com”, “name”: “Test User”, “role”: “viewer”, “is_active”: true, “email_verified”: false, “created_at”: “2026-01-20T…”

}

}

Error responses:

400 - Validation Error: .. code-block:: json

{

“error”: “Email, password, and name are required”

} // OR {

“error”: “Invalid email format”

} // OR {

“error”: “Password must be at least 8 characters long”

}

409 - User Already Exists: .. code-block:: json

{

“error”: “User with this email already exists”

}

500 - Server Error: .. code-block:: json

{

“error”: “Registration failed”

}

Common Issues and Solutions

Issue 1: “Failed to fetch” or Network Error

Symptoms: - Button click does nothing - Network tab shows failed request - Console shows fetch error

Solutions:

  1. Check server is running: `bash # Should see: Next.js 13.5.11 - Local: http://localhost:3001 npm run dev `

  2. Verify correct URL: - Registration page: http://localhost:3001/register - NOT http://localhost:3000/register

  3. Check firewall/antivirus isn’t blocking localhost:3001

Issue 2: “NEXTAUTH_SECRET must be provided”

Symptoms: - 500 error in Network tab - Server logs show NextAuth error

Solution: .. code-block:: bash

# Generate a secure secret openssl rand -base64 32

# Add to .env file echo “NEXTAUTH_SECRET=<generated-secret>” >> .env

# Restart the server npm run dev

Issue 3: “Database not initialized” or MongoDB Connection Error

Symptoms: - 500 error with “Database not initialized” - Server logs show MongoDB connection error

Solutions:

  1. Start MongoDB: ```bash # macOS/Linux sudo systemctl start mongod # OR brew services start mongodb-community

    # Windows net start MongoDB ```

  2. Verify MongoDB is running: `bash mongosh --eval "db.runCommand({ ping: 1 })" `

  3. Check MONGODB_URI: `bash # In .env MONGODB_URI=mongodb://localhost:27017 `

  4. Run migration: `bash npm run migrate:auth `

Issue 4: “User with this email already exists”

Symptoms: - 409 error when trying to register - Same email used before

Solutions:

  1. Use a different email address

  2. Delete existing user (for testing): `bash mongosh earthquake_catalogue db.users.deleteOne({ email: "test@example.com" }) `

  3. Login instead of registering at /login

Issue 5: Form Validation Not Working

Symptoms: - Can submit empty form - No error messages shown - Passwords don’t match but form submits

Check:

  1. Browser console for React errors

  2. Form state in React DevTools

  3. Verify form validation logic: - Email format check - Password length (min 8 characters) - Password confirmation match

Issue 6: Registration Succeeds but Can’t Login

Symptoms: - Registration returns 201 success - Login fails with “Invalid email or password”

Solutions:

  1. Check password was hashed correctly: `bash mongosh earthquake_catalogue db.users.findOne({ email: "test@example.com" }) # Should see password_hash field, NOT plain password `

  2. Verify NextAuth configuration: - Check lib/auth/config.ts exists - Check app/api/auth/[...nextauth]/route.ts exists

  3. Clear browser cookies and try again

Manual Testing Steps

Test 1: Successful Registration

  1. Navigate to http://localhost:3001/register

  2. Fill in form: - Name: “Test User” - Email: “test@example.com” - Password: “password123” - Confirm Password: “password123”

  3. Click “Create account”

  4. Should redirect to /login?registered=true

  5. Login with same credentials

  6. Should redirect to / (home page)

Test 2: Duplicate Email

  1. Try to register with same email again

  2. Should see error: “User with this email already exists”

Test 3: Password Validation

  1. Try password “short” (< 8 chars)

  2. Should see error: “Password must be at least 8 characters long”

Test 4: Password Mismatch

  1. Password: “password123”

  2. Confirm: “password456”

  3. Should see error: “Passwords do not match”

Debugging with curl

Test the API directly:

# Successful registration
curl -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test User",
    "email": "test@example.com",
    "password": "password123"
  }'

# Should return 201 with user object

# Test duplicate email
curl -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test User 2",
    "email": "test@example.com",
    "password": "password456"
  }'

# Should return 409 error

Check Server Logs

Monitor the terminal where npm run dev is running for errors:

Common log messages:
✓ Compiled successfully
✓ Ready in 3.8s
⚠ Port 3000 is in use, trying 3001 instead

Look for errors like: .. code-block:: text

Error: NEXTAUTH_SECRET must be provided MongoServerError: connect ECONNREFUSED TypeError: Cannot read property ‘findOne’ of undefined

Database Verification

Check if user was created:

mongosh earthquake_catalogue

# List all users
db.users.find().pretty()

# Check specific user
db.users.findOne({ email: "test@example.com" })

# Verify password is hashed
db.users.findOne({ email: "test@example.com" }, { password_hash: 1 })
# Should see: password_hash: "$2a$10$..."

Still Having Issues?

  1. Clear all data and start fresh: `bash # Stop server (Ctrl+C) # Drop database mongosh earthquake_catalogue --eval "db.dropDatabase()" # Run migration npm run migrate:auth # Restart server npm run dev `

  2. Check file permissions: `bash ls -la .env # Should be readable `

  3. Verify all files exist: `bash ls -la app/api/auth/register/route.ts ls -la lib/auth/utils.ts ls -la lib/auth/config.ts `

  4. Check for TypeScript errors: `bash npm run build `

Getting Help

When reporting issues, include: 1. Browser console errors (screenshot) 2. Network tab request/response (screenshot) 3. Server terminal output 4. Environment variables (redact secrets!) 5. MongoDB connection status 6. Steps to reproduce

Quick Fix Script

Create a file scripts/test-registration.sh:

#!/bin/bash
echo "Testing registration system..."
echo "1. Checking MongoDB..."
mongosh --eval "db.version()" > /dev/null 2>&1 && echo "✓ MongoDB running" || echo "✗ MongoDB not running"

echo "2. Checking environment..."
grep -q "NEXTAUTH_SECRET" .env && echo "✓ NEXTAUTH_SECRET set" || echo "✗ NEXTAUTH_SECRET missing"

echo "3. Testing API..."
curl -s -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"Test","email":"test@test.com","password":"test1234"}' \
  | jq '.' || echo "✗ API not responding"

echo "Done!"

Run with: bash scripts/test-registration.sh

Registration Debugging Guide

Quick Start - Immediate Actions

Step 1: Update NEXTAUTH_URL

Your server is running on port 3001, not 3000. Update your .env file:

# Change this:
NEXTAUTH_URL=http://localhost:3000

# To this:
NEXTAUTH_URL=http://localhost:3001

Then restart the server: .. code-block:: bash

# Press Ctrl+C to stop npm run dev

Step 2: Run the Test Script

npx tsx scripts/test-registration.ts

This will check: - ✅ Environment variables - ✅ MongoDB connection - ✅ Database collections - ✅ User roles - ✅ API endpoint

Step 3: Use the Test Page

Navigate to: http://localhost:3001/test-registration.html

This standalone test page will: - Show detailed error messages - Display API responses - Log everything to browser console - Work independently of React/Next.js

Debugging Workflow

1. Check Browser Console (F12)

What to look for: - Red errors (JavaScript exceptions) - Network errors (failed fetch requests) - CORS errors - NextAuth errors

Common errors and fixes:

Error

Cause

Fix

Failed to fetch

Server not running or wrong port

Check server is on port 3001

NEXTAUTH_SECRET must be provided

Missing env variable

Add to .env and restart

NetworkError

CORS or network issue

Check server logs

Unexpected token

JSON parsing error

Check API response format

2. Check Network Tab

  1. Open DevTools (F12) → Network tab

  2. Click “Create account”

  3. Look for POST /api/auth/register

Successful request: .. code-block:: text

Status: 201 Created Response: {

“message”: “User registered successfully”, “user”: {

“id”: “user_…”, “email”: “test@example.com”, “name”: “Test User”, “role”: “viewer”, “is_active”: true

}

}

Failed requests:

Status

Error

Solution

400

“Email, password, and name are required”

Fill all fields

400

“Invalid email format”

Use valid email

400

“Password must be at least 8 characters”

Use longer password

409

“User with this email already exists”

Use different email or delete existing user

500

“Registration failed”

Check server logs and MongoDB

3. Check Server Logs

Look at the terminal where npm run dev is running:

Good signs: .. code-block:: text

✓ Compiled successfully ✓ Ready in 3.8s ⚠ Port 3000 is in use, trying 3001 instead

Bad signs: .. code-block:: text

Error: NEXTAUTH_SECRET must be provided MongoServerError: connect ECONNREFUSED TypeError: Cannot read property ‘findOne’ of undefined

4. Test with curl

# Test successful registration
curl -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test User",
    "email": "test@example.com",
    "password": "password123"
  }' | jq '.'

# Expected: 201 status with user object

# Test duplicate email
curl -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test User 2",
    "email": "test@example.com",
    "password": "password456"
  }' | jq '.'

# Expected: 409 status with error message

Common Issues and Solutions

Issue 1: Button Does Nothing

Symptoms: - Click “Create account” button - Nothing happens - No errors in console

Debug steps: 1. Open browser console (F12) 2. Check for JavaScript errors 3. Verify form is submitting: Add console.log('Form submitted') in handleSubmit 4. Check if loading state is stuck

Solution: - Check if there’s a JavaScript error preventing form submission - Verify all required fields are filled - Check browser’s ad blocker isn’t blocking the request

Issue 2: “Failed to fetch” Error

Symptoms: - Error in console: “Failed to fetch” - Network tab shows failed request - Red error in browser

Debug steps: 1. Verify server is running: npm run dev 2. Check correct port: Should be 3001, not 3000 3. Test API directly: curl http://localhost:3001/api/auth/register

Solution: .. code-block:: bash

# Update .env NEXTAUTH_URL=http://localhost:3001

# Restart server npm run dev

# Navigate to correct URL http://localhost:3001/register

Issue 3: “NEXTAUTH_SECRET must be provided”

Symptoms: - 500 error in Network tab - Server logs show NextAuth error

Solution: .. code-block:: bash

# Generate secret openssl rand -base64 32

# Add to .env echo “NEXTAUTH_SECRET=<paste-generated-secret>” >> .env

# Restart server npm run dev

Issue 4: MongoDB Connection Error

Symptoms: - 500 error with “Database not initialized” - Server logs show MongoDB error

Debug steps: 1. Check MongoDB is running:

`bash mongosh --eval "db.version()" `

  1. Test connection: `bash mongosh mongodb://localhost:27017 `

  2. Check .env: `bash grep MONGODB .env `

Solution: .. code-block:: bash

# Start MongoDB sudo systemctl start mongod # OR brew services start mongodb-community

# Run migration npm run migrate:auth

# Restart server npm run dev

Issue 5: User Already Exists

Symptoms: - 409 error - “User with this email already exists”

Solutions:

Option 1: Use different email .. code-block:: text

Option 2: Delete existing user .. code-block:: bash

mongosh earthquake_catalogue db.users.deleteOne({ email: “test@example.com” })

Option 3: Login instead Navigate to /login and use existing credentials

Testing Checklist

  • [ ] Environment variables set (NEXTAUTH_SECRET, NEXTAUTH_URL, MONGODB_URI)

  • [ ] MongoDB is running

  • [ ] Database migration completed (npm run migrate:auth)

  • [ ] Dev server is running on port 3001

  • [ ] Browser console shows no errors

  • [ ] Network tab shows 201 response for successful registration

  • [ ] Can login after registration

Files to Check

If issues persist, verify these files exist and have no syntax errors:

# Core files
ls -la app/(auth)/register/page.tsx
ls -la app/api/auth/register/route.ts
ls -la lib/auth/utils.ts
ls -la lib/auth/config.ts
ls -la lib/auth/types.ts

# Check for TypeScript errors
npm run build

Get More Help

Run the comprehensive test: .. code-block:: bash

npx tsx scripts/test-registration.ts

Use the test page: .. code-block:: text

Check detailed troubleshooting: .. code-block:: text

docs/source/appendix/troubleshooting_registration.rst

Emergency Reset

If nothing works, reset everything:

# 1. Stop server (Ctrl+C)

# 2. Drop database
mongosh earthquake_catalogue --eval "db.dropDatabase()"

# 3. Clear .env and recreate
rm .env
cp .env.example .env

# 4. Add required variables
echo "NEXTAUTH_SECRET=$(openssl rand -base64 32)" >> .env
echo "NEXTAUTH_URL=http://localhost:3001" >> .env
echo "MONGODB_URI=mongodb://localhost:27017" >> .env
echo "MONGODB_DATABASE=earthquake_catalogue" >> .env

# 5. Run migration
npm run migrate:auth

# 6. Start server
npm run dev

# 7. Test
npx tsx scripts/test-registration.ts

Success Criteria

Registration is working when: 1. ✅ Form submits without errors 2. ✅ Network tab shows 201 status 3. ✅ User appears in database 4. ✅ Can login with new credentials 5. ✅ Redirects to login page after registration

Registration Issue - FIXED ✅

Problem

The registration functionality was not working because required environment variables were missing.

Root Cause

The .env file was missing: - NEXTAUTH_SECRET - Required by NextAuth.js for JWT token signing - NEXTAUTH_URL - Required by NextAuth.js to know the application URL

Solution Applied

1. Added Missing Environment Variables

NEXTAUTH_SECRET=<generate-with-openssl-rand-base64-32>
NEXTAUTH_URL=http://localhost:3000

If a real NEXTAUTH_SECRET value was ever committed or published, rotate it in every environment before reusing the application.

2. Ran Database Migration

npm run migrate:auth

This created: - user_roles collection with 4 roles (Admin, Editor, Viewer, Guest) - Indexes on the users collection for authentication - Default role permissions

3. Verified API is Working

Tested with curl: .. code-block:: bash

curl -X POST http://localhost:3000/api/auth/register

-H “Content-Type: application/json” -d ‘{“name”:”Test User”,”email”:”test@example.com”,”password”:”password123”}’

Result: ✅ SUCCESS - User created with ID user_1768898126360_wfwh3u03n

How to Use Registration Now

Option 1: Use the Web Interface

  1. Navigate to: http://localhost:3000/register

  2. Fill in the form: - Name: Your full name - Email: Your email address - Password: At least 8 characters - Confirm Password: Same as password

  3. Click “Create account”

  4. You’ll be redirected to the login page

Option 2: Use the Test Page

  1. Navigate to: http://localhost:3000/test-registration.html

  2. This standalone page shows detailed debugging information

  3. Fill in the form and submit

  4. See the API response in real-time

Option 3: Use the API Directly

curl -X POST http://localhost:3000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Your Name",
    "email": "your@email.com",
    "password": "yourpassword"
  }'

What Was Created

Test User

  • Email: test@example.com

  • Password: password123

  • Role: Viewer (default for new users)

  • Status: Active

You can now login with these credentials at /login

Next Steps

  1. Try registering a new user at /register

  2. Login at /login with your credentials

  3. View your profile at /profile

  4. Create an admin user (optional): ```bash # Register a user first, then manually update in MongoDB: mongosh earthquake_catalogue db.users.updateOne(

    { email: “your@email.com” }, { $set: { role: “admin” } }

Troubleshooting

If registration still doesn’t work:

  1. Check browser console (F12) for errors

  2. Check Network tab for the API request/response

  3. Verify server is running on port 3000

  4. Check environment variables are loaded: `bash cat .env | grep NEXTAUTH `

Files Modified

  • .env - Added NEXTAUTH_SECRET and NEXTAUTH_URL

  • Database - Created user_roles collection and indexes

Testing Checklist

  • [x] Environment variables set

  • [x] Database migration completed

  • [x] API endpoint responding (201 status)

  • [x] User created in database

  • [x] Password hashed correctly

  • [ ] Test web registration form

  • [ ] Test login with created user

  • [ ] Test profile page access

Support

For more help, see: - docs/source/appendix/registration_debug_guide.rst - Quick debugging steps - docs/source/appendix/troubleshooting_registration.rst - Detailed troubleshooting - docs/source/appendix/debug_tools.rst - Browser debugging tools - docs/source/appendix/authentication.rst - Complete authentication documentation