{"id":16229369,"url":"https://github.com/brandonxiang/fastify-starter","last_synced_at":"2026-05-11T05:44:35.140Z","repository":{"id":232389649,"uuid":"769064222","full_name":"brandonxiang/fastify-starter","owner":"brandonxiang","description":"A simplest template to start up a http server","archived":false,"fork":false,"pushed_at":"2025-03-31T20:07:33.000Z","size":226,"stargazers_count":1,"open_issues_count":5,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-31T21:23:34.716Z","etag":null,"topics":["fastify","nodejs","starter","template","templates","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/brandonxiang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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":"2024-03-08T09:14:41.000Z","updated_at":"2025-01-06T02:58:11.000Z","dependencies_parsed_at":"2024-04-09T16:45:17.774Z","dependency_job_id":"0d6d7940-73bb-412b-9485-017749852913","html_url":"https://github.com/brandonxiang/fastify-starter","commit_stats":null,"previous_names":["brandonxiang/fastify-starter"],"tags_count":0,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brandonxiang%2Ffastify-starter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brandonxiang%2Ffastify-starter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brandonxiang%2Ffastify-starter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brandonxiang%2Ffastify-starter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/brandonxiang","download_url":"https://codeload.github.com/brandonxiang/fastify-starter/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246819749,"owners_count":20839094,"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":["fastify","nodejs","starter","template","templates","typescript"],"created_at":"2024-10-10T12:58:10.307Z","updated_at":"2026-05-11T05:44:35.129Z","avatar_url":"https://github.com/brandonxiang.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Fastify Starter 🚀\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/brandonxiang/fastify-starter\"\u003e\n    \u003cimg src=\"https://brandonxiang.top/icon/vite-template.jpeg\" width=\"150px\" alt=\"Template Logo\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\nA modern Fastify starter template powered by **Vite+**, built with TypeScript and industry best practices.\n\n## Vite+ Powered\n\nThis project uses [Vite+](https://vite-plus.dev) - the unified toolchain for the web, providing:\n\n- ⚡ **Lightning Fast** - Powered by Rolldown and Vite\n- 🔧 **All-in-One** - Type checking, linting, formatting in one command\n- 🚀 **Zero Config** - Sensible defaults with full customization\n- 📦 **Smart Dependencies** - Automatic package management via `vp`\n\n## Features\n\n- ⚡ **Fastify 5.x** - Fast and efficient web framework\n- 🔷 **TypeScript** - Full TypeScript support with latest ES2022 features\n- 📚 **Swagger/OpenAPI** - Auto-generated API documentation\n- 🔄 **Hot Reload** - Development server with watch mode\n- ⚙️ **Environment Config** - Flexible configuration management\n- 🗄️ **Database Ready** - Knex.js integration with MySQL\n- 🔗 **Redis Support** - IORedis integration\n- 🛡️ **CORS** - Configurable CORS settings\n- 🧪 **TypeScript Strict Mode** - Enhanced type safety\n- 📦 **Vite+ Powered** - Powered by Rolldown, Vitest, Oxlint\n- 🎨 **Code Quality** - Oxlint + Oxfmt for linting and formatting\n- 🚦 **Health Checks** - Built-in health monitoring\n- 🔧 **Graceful Shutdown** - Proper process management\n\n## Requirements\n\n- Node.js \u003e= 18.0.0\n- Vite+ (install via `npm install -g vite-plus`)\n\n## Quick Start\n\n1. **Clone the repository**\n\n   ```bash\n   git clone \u003crepository-url\u003e\n   cd fastify-starter\n   ```\n\n2. **Install dependencies**\n\n   ```bash\n   vp install\n   ```\n\n3. **Set up environment variables**\n\n   ```bash\n   cp .env.example .env\n   # Edit .env with your configuration\n   ```\n\n4. **Start development server**\n\n   ```bash\n   vp dev\n   ```\n\n5. **Visit your application**\n   - API: \u003chttp://localhost:31303\u003e\n   - Documentation: \u003chttp://localhost:31303/docs\u003e\n   - Health Check: \u003chttp://localhost:31303/health\u003e\n\n## Scripts\n\n| Command              | Description                                      |\n| -------------------- | ------------------------------------------------ |\n| `vp dev`             | Start development server with hot reload         |\n| `vp build`           | Build for production with tree-shaking           |\n| `vp run build:dev`   | Build for development                            |\n| `vp run start`       | Start production server                          |\n| `vp run start:prod`  | Start production server with NODE_ENV=production |\n| `vp check`           | Run TypeScript, lint, and format checks          |\n| `vp lint`            | Run ESLint                                       |\n| `vp lint --fix`      | Run ESLint with auto-fix                         |\n| `vp fmt`             | Format code with Oxfmt                           |\n| `vp fmt --check`     | Check code formatting                            |\n| `vp test`            | Run tests                                        |\n| `vp run deps:check`  | Check for outdated dependencies                  |\n| `vp run deps:update` | Update dependencies                              |\n\n## Project Structure\n\n```\nsrc/\n├── config/          # Configuration management\n│   └── index.ts     # Environment-based configuration\n├── constants/       # Application constants\n├── model/           # Database models (Knex.js)\n│   └── base.ts      # Base model class\n├── redis/           # Redis utilities\n│   └── index.ts     # Redis connection and operations\n├── routes/          # API routes\n│   └── hello.ts     # Example route module\n├── types/           # TypeScript type definitions\n├── utils/           # Utility functions\n│   └── index.ts     # Common utilities\n└── server.ts        # Main application server\n```\n\n## Configuration\n\nThe application uses environment-based configuration. Set these environment variables:\n\n### Core Settings\n\n```bash\nNODE_ENV=development          # Environment (development/production)\nPORT=31303                   # Server port\nHOST=0.0.0.0                # Server host\nAPP_REGION=sg               # Application region\n```\n\n### Database (MySQL)\n\n```bash\nDB_HOST=localhost\nDB_PORT=3306\nDB_USER=root\nDB_PASSWORD=your_password\nDB_DATABASE=fastify_starter\n```\n\n### Redis\n\n```bash\nREDIS_HOST=localhost\nREDIS_PORT=6379\nREDIS_PASSWORD=your_redis_password  # Optional\n```\n\n### CORS\n\n```bash\nCORS_ORIGIN=https://yourdomain.com,https://anotherdomain.com\n```\n\n## API Documentation\n\nThe API documentation is automatically generated using Swagger/OpenAPI and available at `/docs` when running the server.\n\n### Example Endpoints\n\n- `GET /` - Welcome message\n- `GET /health` - Health check\n- `GET /api/hello/world?name=John` - Hello world with optional name\n- `POST /api/hello/user` - Hello with user data\n- `GET /api/hello/info` - Service information\n\n## Modern Fastify Patterns\n\nThis starter implements the latest Fastify conventions:\n\n### 1. Plugin Architecture\n\n```typescript\nconst helloRoutes: FastifyPluginAsync = async (fastify: FastifyInstance) =\u003e {\n  fastify.get('/world', { schema: helloWorldSchema }, async (request, reply) =\u003e {\n    // Route handler\n  });\n};\n```\n\n### 2. Schema-First Approach\n\n```typescript\nconst helloWorldSchema = {\n  description: 'Hello World endpoint',\n  tags: ['hello'],\n  querystring: {\n    type: 'object',\n    properties: {\n      name: { type: 'string', description: 'Name to greet' },\n    },\n  },\n  response: {\n    200: {\n      /* response schema */\n    },\n  },\n} as const;\n```\n\n### 3. TypeScript Integration\n\n```typescript\ninterface HelloWorldQuery {\n  name?: string;\n}\n\nfastify.get\u003c{ Querystring: HelloWorldQuery }\u003e(\n  '/world',\n  {\n    schema: helloWorldSchema,\n  },\n  async (request, reply) =\u003e {\n    const { name = 'World' } = request.query; // Fully typed\n  },\n);\n```\n\n### 4. Error Handling\n\n```typescript\nserver.setErrorHandler(async (error, request, reply) =\u003e {\n  server.log.error(error);\n  return reply.send({\n    error: {\n      message: error.message,\n      statusCode: reply.statusCode,\n      timestamp: new Date().toISOString(),\n      path: request.url,\n    },\n  });\n});\n```\n\n### 5. Graceful Shutdown\n\n```typescript\nconst gracefulShutdown = async (signal: string) =\u003e {\n  server.log.info(`Received ${signal}, shutting down gracefully...`);\n  try {\n    await server.close();\n    process.exit(0);\n  } catch (err) {\n    server.log.error('Error during shutdown:', err);\n    process.exit(1);\n  }\n};\n\nprocess.on('SIGTERM', () =\u003e gracefulShutdown('SIGTERM'));\nprocess.on('SIGINT', () =\u003e gracefulShutdown('SIGINT'));\n```\n\n## Database Integration\n\n### Base Model Class\n\n```typescript\nimport { config } from '../config/index.js';\n\nexport const KnexInstance = knex({\n  client: 'mysql',\n  connection: config.database,\n});\n\nexport default class BasicModel\u003cT extends Record\u003cstring, any\u003e\u003e {\n  private builder: Knex.QueryBuilder;\n  protected knex = KnexInstance;\n\n  constructor(table: string) {\n    this.builder = this.knex\u003cT\u003e(table);\n  }\n\n  async query(condition: Partial\u003cT\u003e): Promise\u003cT[]\u003e {\n    return this.queryBuilder.where(condition).select('*');\n  }\n}\n```\n\n## Redis Integration\n\n```typescript\nimport { config } from '../config/index.js';\n\nconst redis = new IORedis({\n  host: config.redis.host,\n  port: config.redis.port,\n  ...(config.redis.password \u0026\u0026 { password: config.redis.password }),\n});\n\nexport async function hget(key: string, field: string) {\n  return redis.hget(key, field);\n}\n```\n\n## Development\n\n### Adding New Routes\n\n1. Create a new route file in `src/routes/`\n2. Define your schemas and interfaces\n3. Export as FastifyPluginAsync\n4. Register in `src/server.ts`\n\n### Adding New Models\n\n1. Create a model file in `src/model/`\n2. Extend the BasicModel class\n3. Define your entity interface\n4. Add database-specific methods\n\n## Production Deployment\n\n1. **Build the application**\n\n   ```bash\n   vp build\n   ```\n\n2. **Set production environment**\n\n   ```bash\n   export NODE_ENV=production\n   ```\n\n3. **Start the server**\n\n   ```bash\n   vp run start:prod\n   ```\n\n## Best Practices\n\n1. **Use TypeScript strictly** - Enable all strict checks\n2. **Schema validation** - Define schemas for all endpoints\n3. **Error handling** - Implement comprehensive error handling\n4. **Logging** - Use structured logging with Pino\n5. **Configuration** - Use environment-based config\n6. **Security** - Implement proper CORS and security headers\n7. **Testing** - Write tests for your endpoints (TODO: Add testing setup)\n8. **Documentation** - Keep API documentation up to date\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Port already in use**\n\n   ```bash\n   lsof -ti:31303 | xargs kill -9\n   ```\n\n2. **Database connection issues**\n   - Check your database credentials in `.env`\n   - Ensure MySQL is running\n   - Verify network connectivity\n\n3. **Redis connection issues**\n   - Check Redis server status\n   - Verify Redis configuration\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Run tests and linting\n5. Submit a pull request\n\n## License\n\nISC License\n\n---\n\n**Happy coding with Fastify! 🚀**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrandonxiang%2Ffastify-starter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbrandonxiang%2Ffastify-starter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrandonxiang%2Ffastify-starter/lists"}