{"id":20452247,"url":"https://github.com/promehedi/bun-hono-api-starter","last_synced_at":"2026-01-03T15:15:52.830Z","repository":{"id":190667401,"uuid":"683103963","full_name":"ProMehedi/bun-hono-api-starter","owner":"ProMehedi","description":"A REST API using Bun + Hono + MongoDB + TypeScript providing a powerful and efficient platform with a simple CRUD interface for a user model.","archived":false,"fork":false,"pushed_at":"2025-03-08T10:29:24.000Z","size":46,"stargazers_count":65,"open_issues_count":0,"forks_count":12,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-10T05:08:41.229Z","etag":null,"topics":["bun","hono","mongoose","typescript"],"latest_commit_sha":null,"homepage":"https://bun-hono-api.up.railway.app/api/v1","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ProMehedi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-08-25T15:55:36.000Z","updated_at":"2025-03-30T00:55:19.000Z","dependencies_parsed_at":null,"dependency_job_id":"ef6d1a99-d119-4aca-9716-c0d97c4a7e2d","html_url":"https://github.com/ProMehedi/bun-hono-api-starter","commit_stats":null,"previous_names":["promehedi/bun-hono-rest-api","promehedi/bun-hono-api-starter"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ProMehedi%2Fbun-hono-api-starter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ProMehedi%2Fbun-hono-api-starter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ProMehedi%2Fbun-hono-api-starter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ProMehedi%2Fbun-hono-api-starter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ProMehedi","download_url":"https://codeload.github.com/ProMehedi/bun-hono-api-starter/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248161270,"owners_count":21057555,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bun","hono","mongoose","typescript"],"created_at":"2024-11-15T11:06:38.775Z","updated_at":"2026-01-03T15:15:52.823Z","avatar_url":"https://github.com/ProMehedi.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Bun + Hono API Starter\n\nA modern, high-performance API starter template using [Bun](https://bun.sh), [Hono](https://hono.dev), [MongoDB](https://mongodb.com), and TypeScript.\n\n## Features\n\n- ⚡️ **Ultra-fast performance** with Bun runtime\n- 🔄 **Hot reloading** for fast development cycles\n- 🧩 **Modular architecture** for scalability\n- 🔒 **Built-in authentication** middleware and JWT support with expiration\n- 🛡️ **Security-first design** with rate limiting, secure headers, and CSRF protection\n- 🚦 **Request validation** for robust API design\n- 🗃️ **MongoDB integration** with Mongoose\n- 📦 **Compression support** for optimized responses\n- ✅ **TypeScript** for type safety\n- 🔍 **Error handling** middleware with proper stack trace management\n- 🚨 **Rate limiting** to prevent brute force attacks\n- 🔐 **Secure headers** (XSS, clickjacking, MIME sniffing protection)\n\n## Table of Contents\n\n- [Getting Started](#getting-started)\n  - [Prerequisites](#prerequisites)\n  - [Installation](#installation)\n  - [Configuration](#configuration)\n- [Usage](#usage)\n  - [Development](#development)\n  - [Production](#production)\n- [Security](#security)\n- [API Routes](#api-routes)\n- [User Model](#user-model)\n- [Project Structure](#project-structure)\n- [Changelog](#changelog)\n- [Contributing](#contributing)\n- [License](#license)\n- [Contact](#contact)\n\n## Getting Started\n\n### Prerequisites\n\nBefore you begin, make sure you have the following installed:\n\n- [Bun](https://bun.sh) (v1.0.0 or newer)\n- [MongoDB](https://mongodb.com) or [MongoDB Atlas](https://www.mongodb.com/atlas/database)\n\n### Installation\n\n1. Clone this repository:\n\n```bash\ngit clone https://github.com/ProMehedi/bun-hono-api-starter.git\ncd bun-hono-api-starter\n```\n\n2. Install dependencies:\n\n```bash\nbun install\n```\n\n### Configuration\n\nCreate a `.env` file in the root directory with the following variables:\n\n```env\n# Required\nJWT_SECRET=your-super-secret-key-minimum-32-characters-long\nMONGO_URI=mongodb://localhost:27017/bun-hono-api\n\n# Optional\nPORT=8000\nNODE_ENV=development\n\n# Production only (comma-separated list)\nALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com\n```\n\n**Security Note:**\n\n- `JWT_SECRET` must be at least 32 characters long and kept secure\n- Never commit `.env` file to version control\n- In production, set `NODE_ENV=production` and configure `ALLOWED_ORIGINS` for CORS\n\n## Usage\n\n### Development\n\nRun the development server with hot reloading:\n\n```bash\nbun dev\n```\n\n### Production\n\nStart the production server:\n\n```bash\nbun start\n```\n\n## Security\n\nThis starter template includes comprehensive security features:\n\n### 🔐 Authentication \u0026 Authorization\n\n- **JWT-based authentication** with 7-day token expiration\n- **Protected routes** requiring valid JWT tokens\n- **Admin-only routes** with role-based access control\n- **Password hashing** using Bun's built-in bcrypt implementation\n- **Mass assignment protection** - prevents privilege escalation\n\n### 🛡️ Security Middleware\n\n- **Rate Limiting**:\n\n  - Strict rate limiting (5 requests per 15 minutes) on sensitive endpoints (login, register)\n  - Standard rate limiting (60 requests per minute) on general endpoints\n  - Prevents brute force attacks and API abuse\n\n- **Secure Headers**:\n\n  - X-Frame-Options: DENY (prevents clickjacking)\n  - X-XSS-Protection: 1; mode=block (XSS protection)\n  - X-Content-Type-Options: nosniff (prevents MIME sniffing)\n  - Referrer-Policy: strict-origin-when-cross-origin\n  - Content-Security-Policy (in production)\n\n- **CSRF Protection**: Enabled in production mode\n- **CORS Configuration**: Configurable allowed origins for production\n\n### 🔒 Security Best Practices\n\n- ✅ Input validation on all user inputs\n- ✅ Email format validation\n- ✅ Password length requirements (minimum 6 characters)\n- ✅ Error messages don't leak sensitive information\n- ✅ Stack traces only shown in development\n- ✅ Environment variable validation (throws error if missing)\n- ✅ Password hashes never returned in API responses\n- ✅ Admin role cannot be set during user registration\n\n### 🚨 Rate Limiting Details\n\nThe API implements two levels of rate limiting:\n\n1. **Strict Rate Limit** (Login/Register endpoints):\n\n   - 5 requests per 15 minutes per IP\n   - Prevents brute force attacks\n\n2. **Standard Rate Limit** (All other endpoints):\n   - 60 requests per minute per IP\n   - Prevents API abuse\n\nRate limit headers are included in responses:\n\n- `X-RateLimit-Limit`: Maximum requests allowed\n- `X-RateLimit-Remaining`: Remaining requests in current window\n- `X-RateLimit-Reset`: Unix timestamp when limit resets\n- `Retry-After`: Seconds to wait when limit exceeded (429 status)\n\n## API Routes\n\n| Method | Route                   | Description         | Auth Required | Admin Only |\n| ------ | ----------------------- | ------------------- | ------------- | ---------- |\n| GET    | `/api/v1`               | API welcome message | No            | No         |\n| POST   | `/api/v1/users`         | Create a new user   | No            | No         |\n| POST   | `/api/v1/users/login`   | User login          | No            | No         |\n| GET    | `/api/v1/users/profile` | Get user profile    | Yes           | No         |\n| PUT    | `/api/v1/users/profile` | Update user profile | Yes           | No         |\n| GET    | `/api/v1/users`         | Get all users       | Yes           | Yes        |\n| GET    | `/api/v1/users/:id`     | Get user by ID      | Yes           | Yes        |\n\n### Request/Response Examples\n\n**Create User:**\n\n```\nPOST /api/v1/users\n```\n\n**Note:** This endpoint has strict rate limiting (5 requests per 15 minutes)\n\n```json\n{\n  \"name\": \"Mehedi Hasan\",\n  \"email\": \"mehedi@example.com\",\n  \"password\": \"123456\"\n}\n```\n\n**Response:**\n\n```json\n{\n  \"success\": true,\n  \"data\": {\n    \"_id\": \"...\",\n    \"name\": \"Mehedi Hasan\",\n    \"email\": \"mehedi@example.com\",\n    \"isAdmin\": false,\n    \"token\": \"jwt_token_here\"\n  },\n  \"message\": \"User created successfully\"\n}\n```\n\n**Note:** The `isAdmin` field cannot be set via API - it's always `false` for security.\n\n**User Login:**\n\n```\nPOST /api/v1/users/login\n```\n\n**Note:** This endpoint has strict rate limiting (5 requests per 15 minutes) to prevent brute force attacks\n\n```json\n{\n  \"email\": \"mehedi@example.com\",\n  \"password\": \"123456\"\n}\n```\n\n**Response:**\n\n```json\n{\n  \"success\": true,\n  \"data\": {\n    \"_id\": \"...\",\n    \"name\": \"Mehedi Hasan\",\n    \"email\": \"mehedi@example.com\",\n    \"isAdmin\": false,\n    \"token\": \"jwt_token_here\"\n  },\n  \"message\": \"User logged in successfully\"\n}\n```\n\n**Note:** JWT tokens expire after 7 days. Include the token in the `Authorization` header for protected routes.\n\n**Update Profile:**\n\n```\nPUT /api/v1/users/profile\nAuthorization: Bearer your_jwt_token\n```\n\n```json\n{\n  \"name\": \"Updated Name\",\n  \"email\": \"updated@example.com\",\n  \"password\": \"newpassword\"\n}\n```\n\nAll fields are optional. The response will not include the password hash:\n\n**Response:**\n\n```json\n{\n  \"user\": {\n    \"_id\": \"...\",\n    \"name\": \"Updated Name\",\n    \"email\": \"updated@example.com\",\n    \"isAdmin\": false\n  }\n}\n```\n\n**Protected Routes:**\nInclude the JWT token in the Authorization header:\n\n```\nAuthorization: Bearer your_jwt_token\n```\n\n## User Model\n\nThe user model includes the following properties:\n\n```typescript\ninterface IUser extends Document {\n  _id: Schema.Types.ObjectId\n  name: string\n  email: string\n  password: string\n  isAdmin: boolean\n  matchPassword: (pass: string) =\u003e Promise\u003cboolean\u003e\n  createdAt: Date\n  updatedAt: Date\n}\n```\n\nKey features:\n\n- **Password hashing** with Bun's built-in bcrypt implementation (cost: 10)\n- **Automatic email validation** (must match email pattern)\n- **Admin role support** with the `isAdmin` property\n- **Password matching method** for secure authentication\n- **Timestamps** automatically managed by Mongoose\n- **Security**: The `isAdmin` field cannot be set via API endpoints - it must be set directly in the database for security reasons\n\n## Project Structure\n\n```\n├── config/              # Configuration files\n│   ├── compress.config.ts  # Compression configuration\n│   ├── db.config.ts     # Database configuration\n│   └── index.ts         # Config exports\n├── controllers/         # Route controllers\n│   ├── user.controllers.ts # User-related controllers\n│   └── index.ts         # Controller exports\n├── middlewares/         # Hono middlewares\n│   ├── auth.middlewares.ts # Authentication middleware\n│   ├── error.middlewares.ts # Error handling middleware\n│   ├── rateLimit.middlewares.ts # Rate limiting middleware\n│   └── index.ts         # Middleware exports\n├── models/              # Database models\n│   ├── user.model.ts    # User model schema\n│   └── index.ts         # Model exports\n├── routes/              # API routes\n│   ├── user.routes.ts   # User routes\n│   └── index.ts         # Route exports\n├── utils/               # Utility functions\n│   ├── genToken.ts      # JWT token generator\n│   └── index.ts         # Utils exports\n├── server.ts            # Main application entry\n├── .env                 # Environment variables (create this)\n├── .gitignore           # Git ignore file\n├── bun.lock             # Bun lock file\n├── package.json         # Package configuration\n├── README.md            # This file\n├── tsconfig.json        # TypeScript configuration\n└── wrangler.toml        # Cloudflare Workers configuration\n```\n\n## Changelog\n\n### Version 1.1.0 (Latest)\n\n**Security Improvements:**\n\n- 🔒 Fixed critical mass assignment vulnerability - `isAdmin` can no longer be set during registration\n- 🔐 Added JWT token expiration (7 days) with proper validation\n- 🛡️ Implemented rate limiting middleware to prevent brute force attacks\n- 🔒 Added secure headers middleware (XSS, clickjacking, MIME sniffing protection)\n- 🛡️ Added CSRF protection for production environments\n- 🔐 Fixed JWT secret validation - now throws error if missing\n- 🔒 Fixed password hash leak in profile update response\n- 🛡️ Improved CORS configuration with environment-based origin restrictions\n- 🔍 Fixed error handler stack trace exposure logic\n- ✅ Added comprehensive input validation (email format, password length)\n\n**Code Quality:**\n\n- 📦 Removed deprecated `@types/mongoose` dependency\n- 🔄 Standardized environment variable access to `process.env`\n- ✅ Improved TypeScript types and error handling\n- 🔄 Updated to modern Hono JWT API (`sign`/`verify` instead of deprecated `Jwt`)\n- 📝 Enhanced error messages and validation feedback\n\n**Dependencies:**\n\n- Updated to Hono v4.11.3\n- Mongoose v9.1.1 (includes built-in TypeScript types)\n\n### Version 1.0.2\n\n- Complete project restructuring with improved modularity\n- Added compression support with polyfill for `CompressionStream`\n- Enhanced error handling middleware\n- Updated MongoDB connection with better error feedback\n- Improved CORS configuration for better security\n- Updated to latest Hono v4.7.4 and Mongoose v8.12.1\n- Enhanced TypeScript support and typings\n- Standardized export patterns across modules\n- Added admin role functionality with middleware protection\n- Added profile editing functionality\n\n### Version 1.0.0\n\n- Initial release with basic CRUD functionality\n- MongoDB integration\n- JWT-based authentication\n- Basic error handling\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Contact\n\nMehedi Hasan - [admin@promehedi.com](mailto:admin@promehedi.com)\n\nProject Link: [https://github.com/ProMehedi/bun-hono-api-starter](https://github.com/ProMehedi/bun-hono-api-starter)\n\nProject Link: [https://github.com/ProMehedi/bun-hono-api-starter](https://github.com/ProMehedi/bun-hono-api-starter)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpromehedi%2Fbun-hono-api-starter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpromehedi%2Fbun-hono-api-starter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpromehedi%2Fbun-hono-api-starter/lists"}