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.
Installation
Copy the src/auth/ folder into your project and install missing dependencies:
# 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
connectDatabase() call needed.
Configuration
All features are disabled by default. Use createConfig() to enable what you need:
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
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | /register | No | Create account |
| POST | /login | No | Login |
| POST | /logout | Yes | Logout |
| POST | /logout-all | Yes | Logout all devices |
| GET | /me | Yes | Get profile |
| PATCH | /me | Yes | Update profile |
| POST | /change-password | Yes | Change password |
| POST | /forgot-password | No | Request reset token |
| POST | /reset-password | No | Reset with token |
| POST | /verify-email | Yes | Verify with OTP |
| POST | /resend-verification | Yes | Resend OTP |
| GET | /google | No | OAuth redirect |
| GET | /google/callback | No | OAuth callback |
| GET | /login-history | Yes | Login history |
| GET | /sessions | Yes | List sessions |
| DELETE | /sessions/:id | Yes | Revoke session |
Response Format
All endpoints return a consistent JSON structure:
{
"success": true,
"message": "Login successful",
"data": { /* user object, session, etc. */ }
}
{
"success": false,
"message": "The email or password you entered is incorrect",
"error": {
"code": "INVALID_CREDENTIALS"
}
}
Error Codes
| Code | HTTP | Meaning |
|---|---|---|
VALIDATION_ERROR | 400 | Invalid input data |
INVALID_CREDENTIALS | 401 | Wrong email or password |
UNAUTHORIZED | 401 | Not logged in |
FORBIDDEN | 403 | Not allowed |
EMAIL_NOT_VERIFIED | 403 | Must verify email first |
NOT_FOUND | 404 | Resource not found |
CONFLICT | 409 | Email/username taken |
ACCOUNT_LOCKED | 423 | Too many failed attempts |
RATE_LIMITED | 429 | Too many requests |
TOKEN_EXPIRED | 400 | Link expired |
TOKEN_INVALID | 400 | Link invalid or used |
Registration Config
Enable extra fields on the user model:
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
| Option | Default | Description |
|---|---|---|
identifiers | ['email'] | Fields users can log in with |
allowGoogleOAuth | false | Enable Google OAuth |
Session Config
| Option | Default | Description |
|---|---|---|
cookieName | 'sid' | Cookie name |
maxAge | 7 days | Absolute session lifetime |
idleTimeout | 30 minutes | Inactivity timeout |
rotateOnLogin | true | Rotate session ID on login |
secure | true | HTTPS-only cookies |
sameSite | 'lax' | Cookie SameSite attribute |
Security Config
| Option | Default | Description |
|---|---|---|
csrfProtection | true | CSRF double-submit cookie |
helmet | true | Security headers |
accountLockout.enabled | false | Enable lockout |
accountLockout.maxFailedAttempts | 5 | Attempts before lock |
accountLockout.lockDurationMinutes | 15 | Lock 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:
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)