https://github.com/brandonxiang/fastify-starter
A simplest template to start up a http server
https://github.com/brandonxiang/fastify-starter
fastify nodejs starter template templates typescript
Last synced: about 1 month ago
JSON representation
A simplest template to start up a http server
- Host: GitHub
- URL: https://github.com/brandonxiang/fastify-starter
- Owner: brandonxiang
- Created: 2024-03-08T09:14:41.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2025-03-31T20:07:33.000Z (about 1 year ago)
- Last Synced: 2025-03-31T21:23:34.716Z (about 1 year ago)
- Topics: fastify, nodejs, starter, template, templates, typescript
- Language: TypeScript
- Homepage:
- Size: 221 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Fastify Starter ๐
A modern Fastify starter template powered by **Vite+**, built with TypeScript and industry best practices.
## Vite+ Powered
This project uses [Vite+](https://vite-plus.dev) - the unified toolchain for the web, providing:
- โก **Lightning Fast** - Powered by Rolldown and Vite
- ๐ง **All-in-One** - Type checking, linting, formatting in one command
- ๐ **Zero Config** - Sensible defaults with full customization
- ๐ฆ **Smart Dependencies** - Automatic package management via `vp`
## Features
- โก **Fastify 5.x** - Fast and efficient web framework
- ๐ท **TypeScript** - Full TypeScript support with latest ES2022 features
- ๐ **Swagger/OpenAPI** - Auto-generated API documentation
- ๐ **Hot Reload** - Development server with watch mode
- โ๏ธ **Environment Config** - Flexible configuration management
- ๐๏ธ **Database Ready** - Knex.js integration with MySQL
- ๐ **Redis Support** - IORedis integration
- ๐ก๏ธ **CORS** - Configurable CORS settings
- ๐งช **TypeScript Strict Mode** - Enhanced type safety
- ๐ฆ **Vite+ Powered** - Powered by Rolldown, Vitest, Oxlint
- ๐จ **Code Quality** - Oxlint + Oxfmt for linting and formatting
- ๐ฆ **Health Checks** - Built-in health monitoring
- ๐ง **Graceful Shutdown** - Proper process management
## Requirements
- Node.js >= 18.0.0
- Vite+ (install via `npm install -g vite-plus`)
## Quick Start
1. **Clone the repository**
```bash
git clone
cd fastify-starter
```
2. **Install dependencies**
```bash
vp install
```
3. **Set up environment variables**
```bash
cp .env.example .env
# Edit .env with your configuration
```
4. **Start development server**
```bash
vp dev
```
5. **Visit your application**
- API:
- Documentation:
- Health Check:
## Scripts
| Command | Description |
| -------------------- | ------------------------------------------------ |
| `vp dev` | Start development server with hot reload |
| `vp build` | Build for production with tree-shaking |
| `vp run build:dev` | Build for development |
| `vp run start` | Start production server |
| `vp run start:prod` | Start production server with NODE_ENV=production |
| `vp check` | Run TypeScript, lint, and format checks |
| `vp lint` | Run ESLint |
| `vp lint --fix` | Run ESLint with auto-fix |
| `vp fmt` | Format code with Oxfmt |
| `vp fmt --check` | Check code formatting |
| `vp test` | Run tests |
| `vp run deps:check` | Check for outdated dependencies |
| `vp run deps:update` | Update dependencies |
## Project Structure
```
src/
โโโ config/ # Configuration management
โ โโโ index.ts # Environment-based configuration
โโโ constants/ # Application constants
โโโ model/ # Database models (Knex.js)
โ โโโ base.ts # Base model class
โโโ redis/ # Redis utilities
โ โโโ index.ts # Redis connection and operations
โโโ routes/ # API routes
โ โโโ hello.ts # Example route module
โโโ types/ # TypeScript type definitions
โโโ utils/ # Utility functions
โ โโโ index.ts # Common utilities
โโโ server.ts # Main application server
```
## Configuration
The application uses environment-based configuration. Set these environment variables:
### Core Settings
```bash
NODE_ENV=development # Environment (development/production)
PORT=31303 # Server port
HOST=0.0.0.0 # Server host
APP_REGION=sg # Application region
```
### Database (MySQL)
```bash
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your_password
DB_DATABASE=fastify_starter
```
### Redis
```bash
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password # Optional
```
### CORS
```bash
CORS_ORIGIN=https://yourdomain.com,https://anotherdomain.com
```
## API Documentation
The API documentation is automatically generated using Swagger/OpenAPI and available at `/docs` when running the server.
### Example Endpoints
- `GET /` - Welcome message
- `GET /health` - Health check
- `GET /api/hello/world?name=John` - Hello world with optional name
- `POST /api/hello/user` - Hello with user data
- `GET /api/hello/info` - Service information
## Modern Fastify Patterns
This starter implements the latest Fastify conventions:
### 1. Plugin Architecture
```typescript
const helloRoutes: FastifyPluginAsync = async (fastify: FastifyInstance) => {
fastify.get('/world', { schema: helloWorldSchema }, async (request, reply) => {
// Route handler
});
};
```
### 2. Schema-First Approach
```typescript
const helloWorldSchema = {
description: 'Hello World endpoint',
tags: ['hello'],
querystring: {
type: 'object',
properties: {
name: { type: 'string', description: 'Name to greet' },
},
},
response: {
200: {
/* response schema */
},
},
} as const;
```
### 3. TypeScript Integration
```typescript
interface HelloWorldQuery {
name?: string;
}
fastify.get<{ Querystring: HelloWorldQuery }>(
'/world',
{
schema: helloWorldSchema,
},
async (request, reply) => {
const { name = 'World' } = request.query; // Fully typed
},
);
```
### 4. Error Handling
```typescript
server.setErrorHandler(async (error, request, reply) => {
server.log.error(error);
return reply.send({
error: {
message: error.message,
statusCode: reply.statusCode,
timestamp: new Date().toISOString(),
path: request.url,
},
});
});
```
### 5. Graceful Shutdown
```typescript
const gracefulShutdown = async (signal: string) => {
server.log.info(`Received ${signal}, shutting down gracefully...`);
try {
await server.close();
process.exit(0);
} catch (err) {
server.log.error('Error during shutdown:', err);
process.exit(1);
}
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
```
## Database Integration
### Base Model Class
```typescript
import { config } from '../config/index.js';
export const KnexInstance = knex({
client: 'mysql',
connection: config.database,
});
export default class BasicModel> {
private builder: Knex.QueryBuilder;
protected knex = KnexInstance;
constructor(table: string) {
this.builder = this.knex(table);
}
async query(condition: Partial): Promise {
return this.queryBuilder.where(condition).select('*');
}
}
```
## Redis Integration
```typescript
import { config } from '../config/index.js';
const redis = new IORedis({
host: config.redis.host,
port: config.redis.port,
...(config.redis.password && { password: config.redis.password }),
});
export async function hget(key: string, field: string) {
return redis.hget(key, field);
}
```
## Development
### Adding New Routes
1. Create a new route file in `src/routes/`
2. Define your schemas and interfaces
3. Export as FastifyPluginAsync
4. Register in `src/server.ts`
### Adding New Models
1. Create a model file in `src/model/`
2. Extend the BasicModel class
3. Define your entity interface
4. Add database-specific methods
## Production Deployment
1. **Build the application**
```bash
vp build
```
2. **Set production environment**
```bash
export NODE_ENV=production
```
3. **Start the server**
```bash
vp run start:prod
```
## Best Practices
1. **Use TypeScript strictly** - Enable all strict checks
2. **Schema validation** - Define schemas for all endpoints
3. **Error handling** - Implement comprehensive error handling
4. **Logging** - Use structured logging with Pino
5. **Configuration** - Use environment-based config
6. **Security** - Implement proper CORS and security headers
7. **Testing** - Write tests for your endpoints (TODO: Add testing setup)
8. **Documentation** - Keep API documentation up to date
## Troubleshooting
### Common Issues
1. **Port already in use**
```bash
lsof -ti:31303 | xargs kill -9
```
2. **Database connection issues**
- Check your database credentials in `.env`
- Ensure MySQL is running
- Verify network connectivity
3. **Redis connection issues**
- Check Redis server status
- Verify Redis configuration
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests and linting
5. Submit a pull request
## License
ISC License
---
**Happy coding with Fastify! ๐**