Skip to content

makrandgupta/fastify-starter

Repository files navigation

Fastify Starter

A modern, production-ready Fastify-based REST API starter with TypeScript, PostgreSQL, Drizzle ORM, and comprehensive tooling. Features a complete task management system as an example implementation.

✨ Features

πŸš€ Core Framework

  • Fastify 5.x - High-performance web framework
  • TypeScript 5.x - Full type safety and modern JavaScript features
  • ES Modules - Native ES module support
  • Node.js 22+ - Latest LTS version support

πŸ—„οΈ Database & ORM

  • PostgreSQL - Robust relational database
  • Drizzle ORM - Type-safe SQL ORM with excellent TypeScript support
  • Database Migrations - Automated schema management
  • Drizzle Studio - Visual database browser
  • In-Memory Testing - PGlite for fast, isolated tests

πŸ” Authentication & Security

  • JWT Authentication - Stateless token-based auth
  • Request Validation - Zod schema validation

πŸ“š API Documentation

  • OpenAPI 3.0 - Standard API specification
  • Swagger UI - Interactive API documentation
  • Scalar API Reference - Modern API documentation UI
  • Auto-generated Schemas - Zod to OpenAPI transformation
  • Live Documentation - Available at /docs endpoint

πŸ§ͺ Testing & Quality

  • Vitest - Fast unit and integration testing
  • In-Memory Database - Isolated test environment
  • Comprehensive Test Coverage - Route and integration tests
  • ESLint - Code quality and consistency
  • TypeScript Strict Mode - Compile-time type checking
  • Pre-commit Hooks - Automated code quality checks

πŸ”„ Development Experience

  • Hot Reloading - Development server with file watching
  • Pretty Logging - Colored, structured logs with Pino
  • Path Aliases - Clean imports with @/ prefix
  • Auto-route Loading - Automatic route discovery
  • Environment Management - Type-safe configuration

πŸš€ CI/CD & Deployment

  • GitHub Actions - Automated testing and linting
  • PostgreSQL Service - CI database integration
  • Caching - Optimized dependency installation
  • Multi-branch Support - Main and develop workflows

πŸ“¦ Package Management

  • pnpm - Fast, efficient package manager
  • Workspace Support - Monorepo capabilities
  • Lockfile - Reproducible builds

πŸ› οΈ Prerequisites

  • Node.js (v22.14.1 or later)
  • pnpm (v10.8.1 or later)
  • PostgreSQL database running

πŸš€ Getting Started

1. Clone and Install

git clone <repository-url>
cd fastify-starter
pnpm install

2. Environment Setup

cp env.example .env
# Edit .env with your configuration:
# DATABASE_URL=postgresql://user:password@localhost:5432/database
# JWT_SECRET=your-secret-key-at-least-32-characters

3. Database Setup

# Generate and run migrations
pnpm run db:generate
pnpm run db:migrate

# Seed with sample data
pnpm run db:seed

4. Start Development Server

pnpm run dev

The API will be available at http://localhost:3000

πŸ“– API Documentation

  • Interactive Docs: http://localhost:3000/docs
  • OpenAPI JSON: http://localhost:3000/json
  • Health Check: http://localhost:3000/health

πŸ§ͺ Testing

Run Tests

# Run all tests
pnpm test

# Watch mode
pnpm test:watch

# Test-specific database seeding
pnpm run db:seed:test

Test Features

  • In-memory PostgreSQL - Fast, isolated test environment
  • Automatic cleanup - Fresh database state per test
  • JWT mocking - Simplified authentication testing
  • Route testing - Comprehensive endpoint coverage

πŸ—„οΈ Database Management

Available Commands

# Generate migrations from schema changes
pnpm run db:generate

# Apply pending migrations
pnpm run db:migrate

# Open Drizzle Studio (visual database browser)
pnpm run db:studio

# Seed database with sample data
pnpm run db:seed

# Drop all tables (⚠️ destructive)
pnpm run db:drop

Database Features

  • Type-safe schemas - Drizzle ORM with TypeScript
  • Migration management - Version-controlled schema changes
  • Visual browser - Drizzle Studio for data inspection
  • Sample data - Realistic test data generation

πŸ”§ Development Scripts

Core Commands

pnpm run dev          # Start development server with hot reload
pnpm run build        # Build for production
pnpm run start        # Start production server
pnpm run test         # Run test suite
pnpm run test:watch   # Run tests in watch mode

Code Quality

pnpm run lint         # Run ESLint
pnpm run lint:fix     # Fix linting issues automatically
pnpm run type-check   # TypeScript type checking

API Documentation

pnpm run openapi:generate  # Generate OpenAPI specification

πŸ—οΈ Project Structure

src/
β”œβ”€β”€ modules/              # Feature modules
β”‚   β”œβ”€β”€ auth/            # Authentication routes
β”‚   └── task/            # Task management (example)
β”œβ”€β”€ plugins/              # Fastify plugins
β”‚   β”œβ”€β”€ db.ts           # Database connection
β”‚   β”œβ”€β”€ jwt.ts          # JWT authentication
β”‚   β”œβ”€β”€ openapi.ts      # API documentation
β”‚   └── sensible.ts     # Error handling
β”œβ”€β”€ scripts/              # Utility scripts
β”‚   β”œβ”€β”€ db/             # Database management
β”‚   └── test/           # Test configuration
β”œβ”€β”€ index.ts             # Application entry point
└── server.ts           # Server configuration

πŸ” Authentication

JWT Token Generation

For development and testing, generate a test JWT token:

curl http://localhost:3000/auth/token

Protected Routes

Use the authenticate decorator to protect routes:

server.get('/protected', {
  preHandler: server.authenticate()
}, async (request, reply) => {
  // Route logic here
});

🌐 API Endpoints

Authentication

  • GET /auth/token - Generate test JWT token

Tasks (Example Implementation)

  • POST /task - Create a new task
  • GET /task - List all tasks
  • PUT /task/:id - Update a task
  • DELETE /task/:id - Delete a task

System

  • GET /health - Health check endpoint
  • GET /docs - API documentation
  • GET /json - OpenAPI specification

πŸ”„ GitHub Actions

Automated Workflows

Tests (test.yml)

  • Runs on push to main/develop and pull requests
  • Sets up PostgreSQL service container
  • Runs complete test suite
  • Generates test coverage reports

Lint (lint.yml)

  • Runs on push to main/develop and pull requests
  • ESLint code quality checks
  • TypeScript type checking
  • Ensures code consistency

Local Testing

Test the workflows locally:

pnpm lint          # Run linting
pnpm type-check    # Run type checking
pnpm test          # Run tests
pnpm build         # Build project

πŸ”§ Configuration

Environment Variables

NODE_ENV=development          # Environment (development, production, test)
PORT=3000                     # Server port
HOST=0.0.0.0                  # Server host
DATABASE_URL=postgresql://... # PostgreSQL connection string
JWT_SECRET=your-secret-key    # JWT signing secret (min 32 chars)

TypeScript Configuration

  • Strict mode enabled
  • Path aliases configured (@/ prefix)
  • ES modules support
  • Modern target (ES2022)

πŸš€ Production Deployment

Build Process

# Build the application
pnpm run build

# Start production server
pnpm run start

Environment Setup

  1. Set NODE_ENV=production
  2. Configure production DATABASE_URL
  3. Set secure JWT_SECRET
  4. Configure reverse proxy (nginx, etc.)

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all CI checks pass
  6. Submit a pull request

Development Guidelines

  • Follow TypeScript strict mode
  • Write tests for new routes
  • Use ESLint for code quality
  • Follow conventional commit messages
  • Update documentation as needed

πŸ“„ License

[Specify your license here]

πŸ†˜ Support

For issues and questions:

  1. Check the documentation
  2. Review existing issues
  3. Create a new issue with detailed information

Built with ❀️ using Fastify, TypeScript, and Drizzle ORM

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published