Skip to content

A modern, production-ready backend template built with TypeScript, Hono, and Better Auth. Features clean architecture, comprehensive error handling, and built-in observability.

Notifications You must be signed in to change notification settings

ismetcanbyk/hono-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

26 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Hono Backend Template

A modern, production-ready backend template built with TypeScript, Hono, and Better Auth. Features clean architecture, comprehensive error handling, and built-in observability.

✨ Features

  • πŸš€ Fast & Lightweight - Built on Hono, one of the fastest web frameworks
  • πŸ” Authentication - Better Auth with email/password and OAuth support
  • πŸ“Š Observability - Prometheus metrics, Pino logging, health checks
  • πŸ›‘οΈ Security - Rate limiting, CORS, secure headers, input validation
  • πŸ—οΈ Clean Architecture - Separation of concerns, dependency injection
  • πŸ”„ API Versioning - Built-in support for versioned APIs
  • βœ… Type Safety - End-to-end TypeScript with strict checks
  • πŸ§ͺ Production Ready - Graceful shutdown, error handling, validation

πŸ“‹ Prerequisites

  • Node.js 18+
  • MongoDB 4.4+
  • npm or yarn

πŸš€ Quick Start

1. Install Dependencies

npm install

2. Configure Environment

Create a .env file in the root directory:

# Server Configuration
NODE_ENV=development
PORT=3000
LOG_LEVEL=info

# Database
DATABASE_URL=mongodb://localhost:27017/your-database

# Authentication
BETTER_AUTH_SECRET=your-super-secret-key-min-32-characters

# OAuth (Optional)
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
FACEBOOK_CLIENT_ID=
FACEBOOK_CLIENT_SECRET=

3. Start Development Server

npm run dev

The server will start at http://localhost:3000

πŸ“š Available Endpoints

Core Endpoints

  • GET / - API information
  • GET /health - Health check with database status
  • GET /health/liveness - Kubernetes liveness probe
  • GET /health/readiness - Kubernetes readiness probe
  • GET /metrics - Prometheus metrics

API v1

  • POST /api/v1/validate-schema - Test endpoint with validation
  • POST /api/v1/auth/* - Authentication endpoints (Better Auth)
  • GET /api/v1/examples/* - Example error handling endpoints

πŸ—οΈ Project Structure

src/
β”œβ”€β”€ index.ts                    # Application entry point
β”œβ”€β”€ app.ts                      # Application factory
β”œβ”€β”€ server.ts                   # Server lifecycle management
β”œβ”€β”€ config/                     # Configuration layer
β”‚   β”œβ”€β”€ auth.config.ts         # Authentication setup
β”‚   β”œβ”€β”€ database.config.ts     # Database connection
β”‚   β”œβ”€β”€ environment.config.ts  # Environment validation
β”‚   └── index.ts
β”œβ”€β”€ core/                       # Core application logic
β”‚   β”œβ”€β”€ middlewares/           # Middleware functions
β”‚   └── types/                 # Type definitions
β”œβ”€β”€ routes/                     # Route definitions
β”‚   β”œβ”€β”€ v1/                    # API version 1
β”‚   └── health.route.ts
└── schemas/                    # Validation schemas

For detailed architecture documentation, see ARCHITECTURE.md

πŸ”§ Scripts

# Development
npm run dev          # Start development server with hot reload

# Production
npm run build        # Build for production
npm start            # Start production server

# Code Quality
npm run lint         # Run linter
npm run format       # Format code

πŸ›‘οΈ Security Features

  • Rate Limiting - 100 requests per 15 minutes per IP/token
  • CORS - Configurable cross-origin policies
  • Secure Headers - Protection against common vulnerabilities
  • Input Validation - Zod schema validation on all inputs
  • Authentication - Session-based auth with Better Auth
  • Error Sanitization - Sensitive data hidden in production

πŸ“Š Monitoring

Metrics

Prometheus metrics are available at /metrics:

  • HTTP request duration
  • Request count by method/status
  • Active connections
  • Custom business metrics

Logging

Structured JSON logging with Pino:

  • Request/response logging
  • Error logging with stack traces
  • Database operation logging
  • Configurable log levels

Health Checks

  • /health - Overall application health
  • /health/liveness - Is the app running?
  • /health/readiness - Is the app ready to serve traffic?

πŸ” Authentication

This template uses Better Auth with:

  • Email/password authentication
  • Google OAuth (optional)
  • Facebook OAuth (optional)
  • Session management
  • OpenAPI documentation

Auth Endpoints

  • POST /api/v1/auth/sign-up - Register new user
  • POST /api/v1/auth/sign-in - Login
  • POST /api/v1/auth/sign-out - Logout
  • GET /api/v1/auth/session - Get current session

πŸ§ͺ Error Handling

All errors follow a consistent format:

{
	"success": false,
	"error": {
		"code": "ERROR_CODE",
		"message": "Human-readable error message",
		"details": {}
	},
	"timestamp": "2025-01-01T00:00:00.000Z"
}

Error types handled:

  • Validation Errors - Zod schema validation failures
  • HTTP Exceptions - 4xx/5xx errors with proper status codes
  • Database Errors - MongoDB-specific errors
  • Generic Errors - Unexpected errors with stack traces (dev only)

🚒 Deployment

Environment Variables

Ensure all required environment variables are set:

  • NODE_ENV - Set to production
  • DATABASE_URL - MongoDB connection string
  • BETTER_AUTH_SECRET - Secure random string (32+ characters)
  • PORT - Server port (default: 3000)

Docker

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]

Kubernetes

Health check configuration:

livenessProbe:
  httpGet:
    path: /health/liveness
    port: 3000
  initialDelaySeconds: 10
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /health/readiness
    port: 3000
  initialDelaySeconds: 5
  periodSeconds: 5

πŸ“– API Documentation

API documentation is auto-generated via Better Auth's OpenAPI plugin. Access it at:

  • Development: http://localhost:3000/api/v1/auth/openapi

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run linter and tests
  5. Submit a pull request

πŸ“ License

MIT License - feel free to use this template for your projects!

πŸ™ Acknowledgments

Built with:

πŸ“§ Support

For issues and questions, please open a GitHub issue.


Happy coding! πŸš€

About

A modern, production-ready backend template built with TypeScript, Hono, and Better Auth. Features clean architecture, comprehensive error handling, and built-in observability.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors