Documentation

ModularAuth-Kit is a drop-in authentication module for Express.js + MongoDB + TypeScript. Copy the src/auth/ folder into your project and mount it with one function call.

Tip: For the complete, always-up-to-date documentation, visit the docs/ folder on GitHub. This page is a quick reference.

Installation

Copy the src/auth/ folder into your project and install missing dependencies:

terminal
# Install only what's missing from your project: npm install argon2 zod helmet cookie-parser # Add SESSION_SECRET to your .env echo "SESSION_SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")" >> .env
Already have MongoDB connected? The auth module reuses your active Mongoose connection automatically. No connectDatabase() call needed.

Configuration

All features are disabled by default. Use createConfig() to enable what you need:

config example
import { createConfig, createAuthModule } from './auth/index.js'; const config = createConfig({ session: { secure: false }, passwordRecovery: { enabled: true }, emailVerification: { enabled: true }, loginHistory: { enabled: true }, sessionManagement: { enabled: true }, security: { accountLockout: { enabled: true }, }, }); app.use('/auth', createAuthModule(config));

All Endpoints

MethodPathAuthDescription
POST/registerNoCreate account
POST/loginNoLogin
POST/logoutYesLogout
POST/logout-allYesLogout all devices
GET/meYesGet profile
PATCH/meYesUpdate profile
POST/change-passwordYesChange password
POST/forgot-passwordNoRequest reset token
POST/reset-passwordNoReset with token
POST/verify-emailYesVerify with OTP
POST/resend-verificationYesResend OTP
GET/googleNoOAuth redirect
GET/google/callbackNoOAuth callback
GET/login-historyYesLogin history
GET/sessionsYesList sessions
DELETE/sessions/:idYesRevoke session

Response Format

All endpoints return a consistent JSON structure:

Success response
{ "success": true, "message": "Login successful", "data": { /* user object, session, etc. */ } }
Error response
{ "success": false, "message": "The email or password you entered is incorrect", "error": { "code": "INVALID_CREDENTIALS" } }

Error Codes

CodeHTTPMeaning
VALIDATION_ERROR400Invalid input data
INVALID_CREDENTIALS401Wrong email or password
UNAUTHORIZED401Not logged in
FORBIDDEN403Not allowed
EMAIL_NOT_VERIFIED403Must verify email first
NOT_FOUND404Resource not found
CONFLICT409Email/username taken
ACCOUNT_LOCKED423Too many failed attempts
RATE_LIMITED429Too many requests
TOKEN_EXPIRED400Link expired
TOKEN_INVALID400Link invalid or used

Registration Config

Enable extra fields on the user model:

registration fields
createConfig({ registration: { fields: { username: { enabled: true, required: true }, fullName: { enabled: true, required: false }, firstName: { enabled: true, required: true }, lastName: { enabled: true, required: true }, }, }, });

Login Config

OptionDefaultDescription
identifiers['email']Fields users can log in with
allowGoogleOAuthfalseEnable Google OAuth

Session Config

OptionDefaultDescription
cookieName'sid'Cookie name
maxAge7 daysAbsolute session lifetime
idleTimeout30 minutesInactivity timeout
rotateOnLogintrueRotate session ID on login
securetrueHTTPS-only cookies
sameSite'lax'Cookie SameSite attribute

Security Config

OptionDefaultDescription
csrfProtectiontrueCSRF double-submit cookie
helmettrueSecurity headers
accountLockout.enabledfalseEnable lockout
accountLockout.maxFailedAttempts5Attempts before lock
accountLockout.lockDurationMinutes15Lock duration

Password Security

Algorithm: argon2id (OWASP recommended). Parameters: Memory 19 MiB, Iterations 2, Parallelism 1.

Passwords are never stored in plaintext. The passwordHash field is never included in API responses.

Session Security

Sessions are stored server-side in MongoDB. Cookies are httpOnly, signed, and SameSite. Session IDs are rotated on login to prevent fixation attacks.

Token Security

Password reset and email verification tokens are hashed (SHA-256) before database storage. The raw token is sent to the user — only the hash exists in the database. Tokens are single-use and expire after 15 minutes.

Adding Custom Fields

To add fields to the user model, update three places: the Mongoose schema, the TypeScript types, and the Zod validation schema. See the full guide.

Custom Middleware

Add middleware before the auth router mount point:

custom middleware
app.use('/auth', customMiddleware, createAuthModule(config));

Custom Email Provider

Implement the IEmailAdapter interface with your email service (SendGrid, AWS SES, etc.). See the full guide.

Deployment Checklist

Before deploying to production:

  • Set NODE_ENV=production
  • Set session.secure: true (requires HTTPS)
  • Use a strong, unique SESSION_SECRET
  • Enable CSRF protection
  • Enable account lockout
  • Use Nodemailer with real SMTP credentials
  • Configure a reverse proxy (nginx, Cloudflare)
Full documentation is available on GitHub →