Skip to content

Releases: ProMehedi/bun-hono-api-starter

v1.2.1

06 Jan 09:31

Choose a tag to compare

Release Notes - Version 1.2.1

🎉 New Feature: Comprehensive Logging System

Version 1.2.1 introduces a powerful, production-ready logging system built with Winston and daily log rotation. This release adds comprehensive HTTP request logging and structured logging capabilities to help you monitor and debug your API effectively.


✨ What's New

📝 Winston Logger Integration

  • Structured JSON Logging: Production-ready structured logging with JSON format for easy parsing and analysis
  • Human-Readable Console Output: Beautiful, colorized console logs for development with timestamps and metadata
  • Daily Log Rotation: Automatic daily log file rotation with compression to manage disk space efficiently
  • Multiple Log Levels: Support for debug, info, warn, and error log levels with configurable defaults

🔄 HTTP Request Logging Middleware

Every HTTP request is now automatically logged with comprehensive details:

  • HTTP method (GET, POST, PUT, DELETE, etc.)
  • Request path and full URL
  • Response status code
  • Request duration (in milliseconds)
  • User agent information
  • Client IP address (supports Cloudflare and proxy headers)

Example Log Entry:

{
  "timestamp": "2026-01-06T10:30:45.123Z",
  "level": "info",
  "message": "HTTP Request",
  "method": "POST",
  "path": "/api/v1/users/login",
  "url": "http://localhost:8000/api/v1/users/login",
  "status": 200,
  "duration": "45ms",
  "userAgent": "Mozilla/5.0...",
  "ip": "127.0.0.1"
}

📊 Organized Log Files

The logger creates separate log files for different purposes:

  1. App Logs (app-YYYY-MM-DD.log)

    • General application logs (info, warn, error)
    • Max size: 50MB per file
    • Retention: 14 days
    • Compressed after rotation
  2. Error Logs (error-YYYY-MM-DD.log)

    • Error-level logs only
    • Max size: 20MB per file
    • Retention: 30 days
    • Compressed after rotation
  3. Debug Logs (debug-YYYY-MM-DD.log)

    • Debug-level logs (only when LOG_LEVEL=debug)
    • Max size: 100MB per file
    • Retention: 3 days (short retention due to verbosity)
    • Compressed after rotation
  4. Exception Logs (exceptions-YYYY-MM-DD.log)

    • Uncaught exceptions
    • Max size: 20MB per file
    • Retention: 30 days
  5. Rejection Logs (rejections-YYYY-MM-DD.log)

    • Unhandled promise rejections
    • Max size: 20MB per file
    • Retention: 30 days

⚙️ Flexible Configuration

Configure logging behavior using environment variables:

LOG_LEVEL (Optional):

  • debug - Most verbose, includes debug logs
  • info - Standard logging (default in production)
  • warn - Warnings and errors only
  • error - Errors only
  • Default: debug in development, info in production

LOG_TO_FILE (Optional):

  • console - Log to console only
  • file - Log to files only
  • both - Log to both console and files (default)
  • auto - Console in development, files in production
  • Default: both

🔍 Context Logger Helper

Added createContextLogger utility function for structured logging with custom context:

import { createContextLogger } from '~/utils/logger'

const contextLogger = createContextLogger({ userId: '123', requestId: 'abc' })
contextLogger.info('User action', { action: 'login' })
// Logs: { userId: '123', requestId: 'abc', action: 'login' }

📦 Dependencies Added

  • winston v3.19.0 - Powerful logging library for Node.js
  • winston-daily-rotate-file v5.0.0 - Daily log rotation transport for Winston

📁 File Structure Changes

New Files

  • utils/logger.ts - Winston logger configuration and setup
  • middlewares/logger.middlewares.ts - HTTP request logging middleware
  • logs/ - Directory for log files (created automatically)
    • logs/.audit/ - Audit files for log rotation tracking

Updated Files

  • server.ts - Added logger middleware integration
  • package.json - Added Winston dependencies

🚀 Migration Guide

For New Projects

No migration needed! The logger is automatically enabled and will start logging immediately.

For Existing Projects

  1. Install dependencies:

    bun install
  2. Optional: Configure logging in your .env file:

    LOG_LEVEL=info
    LOG_TO_FILE=both
  3. Create logs directory (optional, created automatically):

    mkdir -p logs/.audit
  4. Add to .gitignore (if not already present):

    logs/
    

📝 Usage Examples

Development Setup

LOG_LEVEL=debug
LOG_TO_FILE=both

This will show verbose logs in the console and also save them to files.

Production Setup

LOG_LEVEL=info
LOG_TO_FILE=file

This will only log to files, reducing console noise and improving performance.

Debugging Setup

LOG_LEVEL=debug
LOG_TO_FILE=console

This will show all logs in the console for quick debugging.


🎯 Benefits

  • Better Observability: Track all HTTP requests and responses with detailed metadata
  • Easier Debugging: Structured logs make it easy to find and analyze issues
  • Production Ready: Automatic log rotation prevents disk space issues
  • Flexible Configuration: Adapt logging to your environment needs
  • Performance Monitoring: Request duration logging helps identify slow endpoints
  • Security Auditing: IP and user agent logging helps track suspicious activity

🔧 Technical Details

  • Logs are stored in the logs/ directory at the project root
  • Old log files are automatically compressed (.gz) after rotation
  • Audit files are stored in logs/.audit/ for rotation tracking
  • Logger automatically handles uncaught exceptions and unhandled rejections
  • Exit on handled exceptions in production (configurable)

📚 Documentation

For complete documentation on the logging feature, see the Logging section in the README.


🙏 Thank You

Thank you for using Bun + Hono API Starter! If you have any questions or feedback, please open an issue on GitHub.


Full Changelog: v1.2.0...v1.2.1

v1.2.0

04 Jan 18:56

Choose a tag to compare

TypeScript Fixes:

  • ✅ Fixed IUser interface type incompatibility - changed Schema.Types.ObjectId to Types.ObjectId for proper TypeScript type checking
  • ✅ Fixed Mongoose pre-save hook - removed deprecated next() callback in favor of modern async/await pattern
  • ✅ Improved type safety with correct Mongoose TypeScript types
  • ✅ All TypeScript compilation errors resolved

Code Quality & Developer Experience:

  • 🔧 Updated user model to use modern Mongoose async hook pattern
  • 📝 Fixed typo in comment ("Heiger" → "Higher")
  • 🎨 Added Prettier code formatting with comprehensive configuration
  • 🪝 Integrated Husky git hooks for automated code quality checks
    • pre-commit hook: Automatically runs format:check and typecheck before commits
    • pre-push hook: Ensures code formatting and type checking pass before pushing
  • 📦 Added format scripts: format (auto-fix) and format:check (verify only)
  • ✅ Automatic code quality enforcement prevents committing unformatted or type-unsafe code

v1.1.0

03 Jan 13:32

Choose a tag to compare

Security Improvements:

  • 🔒 Fixed critical mass assignment vulnerability - isAdmin can no longer be set during registration
  • 🔐 Added JWT token expiration (7 days) with proper validation
  • 🛡️ Implemented rate limiting middleware to prevent brute force attacks
  • 🔒 Added secure headers middleware (XSS, clickjacking, MIME sniffing protection)
  • 🛡️ Added CSRF protection for production environments
  • 🔐 Fixed JWT secret validation - now throws error if missing
  • 🔒 Fixed password hash leak in profile update response
  • 🛡️ Improved CORS configuration with environment-based origin restrictions
  • 🔍 Fixed error handler stack trace exposure logic
  • ✅ Added comprehensive input validation (email format, password length)

Code Quality:

  • 📦 Removed deprecated @types/mongoose dependency
  • 🔄 Standardized environment variable access to process.env
  • ✅ Improved TypeScript types and error handling
  • 🔄 Updated to modern Hono JWT API (sign/verify instead of deprecated Jwt)
  • 📝 Enhanced error messages and validation feedback

Dependencies:

  • Updated to Hono v4.11.3
  • Mongoose v9.1.1 (includes built-in TypeScript types)