Smart Library Docs

Utilities

Backend utility modules — database connection, email service, Redis client, IP extraction, audit logging, and error handling.

Utilities

Utility modules provide shared, infrastructure-level functionality used across the backend.


1. Database Connection

File: backend/utils/db.js

Establishes the MongoDB connection using Mongoose.

const connectDB = async () => {
  const conn = await mongoose.connect(process.env.DATABASE_URL);
  console.log(`MongoDB Connected: ${conn.connection.host}`);
};
  • Connection string: process.env.DATABASE_URL
  • Fatal on failure — calls process.exit(1) so the server doesn't run without a database
  • Called once at startup from server.js

2. Redis Client

File: backend/utils/redisClient.js

Manages the Redis connection for distributed rate limiting.

EnvironmentBehavior
REDIS_URL presentConnects via ioredis
Production without REDIS_URLFails startup (Redis is mandatory)
Development without REDIS_URLFalls back to null (in-memory rate limiting)

The exported client is consumed by middleware/rateLimiter.js to decide between RateLimiterRedis and RateLimiterMemory.


3. API Error Class

File: backend/utils/apiError.js

Custom error class with machine-readable error codes:

class APIError extends Error {
  constructor(message, statusCode, code = 'SERVER_ERROR', errors = null, isOperational = true)
}
PropertyDescription
messageHuman-readable error description
statusCodeHTTP status code (400, 401, 404, 500, etc.)
codeMachine-readable identifier (e.g., VALIDATION_FAILED)
errorsOptional field-level validation errors object
isOperationalDistinguishes expected errors from programming bugs

4. Async Handler

File: backend/utils/asyncHandler.js

Wraps async Express route handlers to automatically catch errors and forward them to next():

const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

Eliminates the need for try/catch blocks in every controller method.


5. Client IP Extraction

File: backend/utils/getClientIp.js

Cloudflare-aware IP extraction with a strict priority chain:

  1. CF-Connecting-IP (Cloudflare)
  2. X-Forwarded-For (first entry)
  3. req.ip (Express)
  4. req.connection.remoteAddress (direct)

Used by all rate limiters to correctly identify clients behind CDNs.


6. Audit Logger

File: backend/utils/auditLogger.js

Logs security-sensitive events to the AuditLog collection.

auditLogger.logSecurityEvent({
  action: 'LOGIN_SUCCESS',
  status: 'SUCCESS',
  userId: user._id,
  ipAddress: '192.168.1.1',
  userAgent: 'Mozilla/5.0...'
});

Logged events include: LOGIN_SUCCESS, LOGIN_FAILED, ACCOUNT_LOCKED, REGISTER, LOGOUT, TOKEN_REFRESHED, PASSWORD_CHANGED.


7. Validators

File: backend/utils/validators.js

Zod-based validation schemas for request body validation.


8. Mailer

File: backend/utils/mailer.js

Sends transactional emails using nodemailer:

  • Welcome emails on registration
  • Book issued / returned notifications
  • Overdue notices
  • Password reset links

Uses SMTP configured via SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS environment variables.


9. Email Service

File: backend/services/emailService.js

Higher-level email service built on top of the mailer utility. Provides template functions:

FunctionPurpose
sendVerificationEmail(user, req)Email verification link
sendPasswordResetEmail(user, req)Password reset link (30 min expiry)
sendEmail(options)Generic send with audit logging

All email operations are logged to the audit system (success and failure).


10. Security Monitor

File: backend/services/securityMonitor.js

Monitors for security anomalies and suspicious activity patterns.


11. Environment Validator

File: backend/config/envValidator.js

Validates all environment variables at startup using Zod schemas:

const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']),
  PORT: z.string().regex(/^\d+$/),
  DATABASE_URL: z.string().url(),
  FRONTEND_URL: z.string().url(),
  SMTP_HOST: z.string().optional(),
  // ...
});

If validation fails, the process exits with detailed error messages.


12. Dependency Scanner

File: backend/config/dependencyScanner.js

Scheduled CRON task that scans package.json dependencies for known vulnerabilities in production.

On this page