Skip to content

A professional backend boilerplate built with Fastify, Prisma, and JWT authentication. This project provides a solid foundation for building scalable web applications with user management, database operations, and security features.

License

Notifications You must be signed in to change notification settings

truongnq2k/fastify-prisma-jwt-boilerplate

Repository files navigation

Fastify Prisma JWT Boilerplate

A professional backend boilerplate built with Fastify, Prisma, and JWT authentication. This project provides a solid foundation for building scalable web applications with user management, database operations, and security features.

🚀 Features

  • 🏗️ Modern Architecture: Built with Fastify for high performance and low overhead
  • 🗄️ Database Management: Prisma ORM with MySQL support
  • 🔐 Authentication: JWT-based authentication system
  • 🛡️ Security: CORS support, request validation, and secure headers
  • 🎯 TypeScript: Full TypeScript support with strict typing
  • 🔧 Development Tools: Hot reload, Prisma Studio, and comprehensive scripts
  • 📊 Health Monitoring: Built-in health check and monitoring endpoints
  • 🚦 Background Jobs: Automated task scheduling with cron jobs
  • 📝 Response Standardization: Consistent API response formatting

🛠️ Tech Stack

Core Technologies

  • Node.js: Runtime environment (v20.19.4 recommended)
  • Fastify: Fast and low-overhead web framework
  • TypeScript: Type-safe JavaScript
  • Prisma: Next-generation ORM
  • MySQL: Database system

Authentication & Security

  • JWT (JSON Web Tokens): Stateless authentication
  • bcryptjs: Password hashing
  • CORS: Cross-origin resource sharing
  • Request Validation: Input sanitization and validation

Development Tools

  • Prisma Studio: Database management interface
  • ts-node-dev: TypeScript development server with hot reload
  • JavaScript Obfuscator: Code protection for production

📋 Prerequisites

Before starting, ensure you have the following installed:

  • Node.js: v20.19.4 or higher
  • MySQL: Database server (mysqlnd 8.2.27 or equivalent)
  • phpMyAdmin: Database management tool (optional)
  • Windows Server IIS or any Windows machine for development

🏗️ Project Structure

├── src/
│   ├── controllers/         # Request handlers
│   │   └── user.controller.ts
│   ├── middleware/          # Authentication middleware
│   │   └── auth.ts
│   ├── routes/              # API route definitions
│   │   ├── user.routes.ts
│   ├── services/            # Business logic
│   │   └── user.service.ts
│   ├── types/               # TypeScript type definitions
│   │   └── user.d.ts
│   ├── utils/               # Utility functions
│   │   ├── prisma.ts
│   │   └── response.ts
│   ├── jobs/                # Background jobs
│   │   └── index.ts
│   └── server.ts            # Main application entry point
├── prisma/                  # Database schema and migrations
│   ├── schema.prisma
│   └── seed.ts
└── dist/                    # Compiled TypeScript output

🚀 Installation & Setup

1. Clone the Repository

git clone https://github.com/truongnq2k/fastify-prisma-jwt-boilerplate.git
cd fastify-prisma-jwt-boilerplate

2. Install Dependencies

npm install

3. Database Setup

Option A: Using Docker (Recommended)

cd docker-db
docker compose up -d

Option B: Manual MySQL Setup

  1. Create a MySQL database
  2. Update DATABASE_URL in your .env file

4. Prisma Setup

# Generate Prisma client
npm run prisma:generate

# Run database migrations
npm run prisma:migrate

# Seed the database with initial data
npm run prisma:seed

5. Environment Configuration

# Copy environment template
cp .env.example .env

# Edit .env with your configuration
nano .env

6. Playwright Installation (if needed)

npx playwright install

⚙️ Environment Variables

Create a .env file in the project root:

# Server Configuration
PORT=8888
HOST=localhost

# Database
DATABASE_URL="mysql://username:password@localhost:3306/database_name"

# JWT Configuration
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"

# Security
CORS_ORIGINS=http://localhost:9999,http://127.0.0.1:9999,http://localhost:3000,https://yourdomain.com
X_HEADER_KEY="your-custom-header-key-for-api-authentication"

🚦 Development

Start Development Server

npm run dev

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

Database Management

# Open Prisma Studio (database GUI)
npm run prisma:studio

# Generate Prisma client
npm run prisma:generate

# Create and apply migrations
npm run prisma:migrate

# Seed database with initial data
npm run prisma:seed

Build for Production

npm run build
npm start

📊 API Documentation

Base URL

  • Development: http://localhost:8888/api
  • Production: https://yourdomain.com/api

Authentication

All protected routes require:

  • JWT Token: Include in Authorization header as Bearer <token>
  • API Key: Include in x-api-key header (value from X_HEADER_KEY)

Endpoints

User Management

  • POST /api/auth/signup - Register new user
  • POST /api/auth/login - User login
  • GET /api/users - Get all users (admin only)
  • GET /api/users/:id - Get user by ID
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user

Health Check

  • GET /health - Server health status

Response Format

All API responses follow this format:

Success Response:

{
  "success": true,
  "message": "Operation successful",
  "data": { ... }
}

Error Response:

{
  "success": false,
  "message": "Error description",
  "error": "Detailed error information"
}

🔧 Scripts

Command Description
npm run dev Start development server with hot reload
npm run build Build TypeScript and prepare for production
npm start Start production server
npm run prisma:generate Generate Prisma client
npm run prisma:migrate Run database migrations
npm run prisma:studio Open Prisma Studio GUI
npm run prisma:seed Seed database with initial data

🛡️ Security Features

  • JWT Authentication: Stateless token-based authentication
  • Password Hashing: Secure password storage using bcryptjs
  • CORS Protection: Configurable cross-origin resource sharing
  • Request Validation: Input sanitization and validation
  • API Key Protection: Additional security layer for sensitive operations
  • Rate Limiting: Built-in rate limiting for API endpoints
  • Helmet Security: Security headers for enhanced protection

📝 Database Schema

Users Table

  • id: Primary key
  • email: Unique email address
  • password: Hashed password
  • name: User display name
  • role: User role (ADMIN/USER)
  • createdAt/updatedAt: Timestamps

Binance Accounts Table

  • Extended features for Binance integration
  • Proxy support configuration
  • Authentication state management

Transactions Table

  • Transaction management and tracking
  • Status monitoring and logging

🔄 Background Jobs

The application includes automated background tasks:

  • Cron Scheduling: feat: configurable task scheduling

🐳 Docker Support

For consistent development environment, use Docker:

cd docker-db
docker compose up -d

This sets up MySQL database with proper configuration.

🤝 Contributing

We follow Conventional Commits specification.

Commit Format

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

Commit Types

  • feat: A new feature
  • fix: A bug fix
  • docs: Documentation only changes
  • style: Changes that do not affect the meaning of the code
  • refactor: A code change that neither fixes a bug nor adds a feature
  • perf: A code change that improves performance
  • test: Adding missing tests or correcting existing tests
  • build: Changes that affect the build system or external dependencies
  • ci: Changes to our CI configuration files and scripts
  • chore: Other changes that don't modify src or test files
  • revert: Reverts a previous commit

Example Commits

feat(auth): add JWT token refresh functionality
fix(database): resolve connection timeout issue
docs(readme): update installation instructions
style(formatting): standardize code indentation
refactor(auth): simplify authentication middleware
test(auth): add unit tests for login endpoint
build(deps): upgrade prisma to version 5.0.0
ci(github): add automated testing workflow

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/auth-refresh)
  3. Make your changes and follow conventional commits
  4. Push to the branch (git push origin feature/auth-refresh)
  5. Open a Pull Request with a clear title following conventional commits

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the existing documentation
  • Review the code comments and examples

🚀 Production Deployment

  1. Environment Setup: Configure production environment variables
  2. Database: Set up production database and update connection string
  3. Build: Run npm run build to compile TypeScript
  4. Security: Change all default secrets and keys
  5. Monitoring: Set up logging and monitoring
  6. SSL: Configure HTTPS/SSL certificates
  7. Process Manager: Use PM2 or similar for process management

📈 Performance Optimization

  • Database Indexing: Proper indexing strategies
  • Connection Pooling: Optimized database connections
  • Caching: Redis integration for caching (optional)
  • Load Balancing: Horizontal scaling support
  • CDN: Static asset optimization

Built with ❤️ using Fastify, Prisma, and TypeScript

About

A professional backend boilerplate built with Fastify, Prisma, and JWT authentication. This project provides a solid foundation for building scalable web applications with user management, database operations, and security features.

Topics

Resources

License

Stars

Watchers

Forks