This guide covers setting up both MongoDB and PostgreSQL for the authentication system.
The authentication system supports two database types:
- MongoDB - Document-based NoSQL database (Mongoose ORM)
- PostgreSQL - Relational SQL database (Sequelize ORM)
The system automatically detects which database to use based on your configuration and handles all schema creation and migrations.
# Install via Homebrew
brew tap mongodb/brew
brew install mongodb-community
# Start MongoDB as a service
brew services start mongodb-community
# Or run manually
mongod --config /usr/local/etc/mongod.conf# Import MongoDB GPG key
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
# Add MongoDB repository
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# Install MongoDB
sudo apt-get update
sudo apt-get install -y mongodb-org
# Start MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod# Download installer from https://www.mongodb.com/try/download/community
# Run the installer and follow the setup wizard
# MongoDB will be installed as a Windows service# Check if MongoDB is running
mongosh
# You should see the MongoDB shell
# Type 'exit' to quitCreate a configuration file for MongoDB:
simpleauth.config.js
require('dotenv').config();
module.exports = {
sessionSecret: process.env.SECRET_KEY,
database: {
type: 'mongodb',
uri: process.env.MONGODB_URI || 'mongodb://localhost:27017/simpleauth',
autoSync: true,
},
security: {
enableHelmet: true,
enableCsrf: false,
enableRateLimiting: true,
},
};Environment Variables (.env)
SECRET_KEY=your-secret-key-here
MONGODB_URI=mongodb://localhost:27017/simpleauthThe system automatically creates the following collections:
- users - User accounts with authentication data
- refresh_tokens - JWT refresh tokens
- audit_logs - Security audit trail
- sessions - Active user sessions
- device_fingerprints - Trusted device tracking
- login_histories - Login attempt records
- risk_assessments - Risk analysis results
- webauthn_credentials - Passkey/biometric credentials
Indexes are automatically created on critical fields for performance.
# Install via Homebrew
brew install postgresql@15
# Start PostgreSQL
brew services start postgresql@15
# Create database
createdb simpleauth# Install PostgreSQL
sudo apt-get update
sudo apt-get install postgresql postgresql-contrib
# Start PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql
# Create database
sudo -u postgres createdb simpleauth# Download installer from https://www.postgresql.org/download/windows/
# Run the installer and follow the setup wizard
# Use pgAdmin or psql to create databasesimpleauth.config.js
require('dotenv').config();
module.exports = {
sessionSecret: process.env.SECRET_KEY,
database: {
type: 'postgres',
autoSync: true,
alterTables: false,
},
security: {
enableHelmet: true,
enableCsrf: false,
enableRateLimiting: true,
},
};Environment Variables (.env)
SECRET_KEY=your-secret-key-here
DB_HOST=localhost
DB_PORT=5432
DB_NAME=simpleauth
DB_USER=postgres
DB_PASSWORD=your-passwordSequelize Configuration (utils/sequelize.js)
The system uses the existing Sequelize configuration from your utils/sequelize.js file.
# Install Sequelize CLI globally
npm install -g sequelize-cli
# Run migrations
npx sequelize-cli db:migrate
# Rollback last migration
npx sequelize-cli db:migrate:undo
# Rollback all migrations
npx sequelize-cli db:migrate:undo:allThe migrations create the following tables:
- Users - User accounts
- RefreshTokens - JWT refresh tokens
- AuditLogs - Security audit trail
- Sessions - Active sessions
- DeviceFingerprints - Trusted devices
- LoginHistories - Login records
- RiskAssessments - Risk analysis
- WebAuthnCredentials - Passkeys
When you initialize the authentication system, it automatically:
- Connects to the configured database
- Creates all necessary schemas/tables
- Sets up indexes for performance
- Validates the connection
const express = require('express');
const simpleAuth = require('simpleauth');
const app = express();
await simpleAuth(app, {
sessionSecret: 'your-secret',
database: {
type: 'mongodb',
uri: 'mongodb://localhost:27017/myapp',
autoSync: true,
},
});- type:
'mongodb'or'postgres' - uri: Connection string (MongoDB only)
- autoSync: Automatically create schemas/tables (default: true)
- alterTables: Modify existing tables to match models (PostgreSQL only, default: false)
- required: Fail startup if database connection fails (default: true)
To switch between MongoDB and PostgreSQL:
- Update the
database.typein your config - Update environment variables for connection details
- Restart your application
- The system will automatically use the correct ORM and models
Use the database utility to access models:
const { getModels, getDatabaseType } = require('simpleauth/utils/database');
const models = getModels();
// Works with both MongoDB and PostgreSQL
const users = await models.User.find(); // MongoDB
const users = await models.User.findAll(); // PostgreSQL
// Check which database is being used
const dbType = getDatabaseType(); // 'mongodb' or 'postgres'- Use indexes on frequently queried fields (automatically created)
- Enable replica sets for production
- Set up regular backups with
mongodump - Use connection pooling (handled automatically)
- Run migrations in production, not autoSync
- Use connection pooling
- Set up regular backups with
pg_dump - Monitor query performance with EXPLAIN
- Use strong passwords for database users
- Restrict database access to localhost in development
- Use connection encryption (SSL/TLS) in production
- Never commit database credentials to version control
- Use environment variables for all sensitive config
# Check if MongoDB is running
brew services list | grep mongodb # macOS
sudo systemctl status mongod # Linux
# Check logs
tail -f /usr/local/var/log/mongodb/mongo.log # macOS
sudo tail -f /var/log/mongodb/mongod.log # Linux
# Test connection
mongosh mongodb://localhost:27017# Check if PostgreSQL is running
brew services list | grep postgresql # macOS
sudo systemctl status postgresql # Linux
# Check logs
tail -f /usr/local/var/log/postgresql@15.log # macOS
sudo tail -f /var/log/postgresql/postgresql-15-main.log # Linux
# Test connection
psql -U postgres -d simpleauthECONNREFUSED
- Database is not running
- Check connection string/environment variables
- Verify host and port
Authentication Failed
- Check username and password
- Verify database user permissions
- Reset database password if needed
Database Does Not Exist
- Create database manually
- MongoDB: automatically created on first connection
- PostgreSQL: use
createdbcommand
// Connection with performance options
database: {
type: 'mongodb',
uri: 'mongodb://localhost:27017/simpleauth?maxPoolSize=10&w=majority',
autoSync: true,
}// Sequelize connection pool
database: {
type: 'postgres',
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
}# Show current operations
mongosh --eval "db.currentOp()"
# Database statistics
mongosh --eval "db.stats()"
# Collection statistics
mongosh --eval "db.users.stats()"-- Active connections
SELECT * FROM pg_stat_activity;
-- Database size
SELECT pg_size_pretty(pg_database_size('simpleauth'));
-- Table sizes
SELECT schemaname, tablename,
pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename))
FROM pg_tables WHERE schemaname = 'public';