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.
- 🏗️ 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
- 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
- JWT (JSON Web Tokens): Stateless authentication
- bcryptjs: Password hashing
- CORS: Cross-origin resource sharing
- Request Validation: Input sanitization and validation
- Prisma Studio: Database management interface
- ts-node-dev: TypeScript development server with hot reload
- JavaScript Obfuscator: Code protection for production
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
├── 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
git clone https://github.com/truongnq2k/fastify-prisma-jwt-boilerplate.git
cd fastify-prisma-jwt-boilerplatenpm installOption A: Using Docker (Recommended)
cd docker-db
docker compose up -dOption B: Manual MySQL Setup
- Create a MySQL database
- Update
DATABASE_URLin your.envfile
# Generate Prisma client
npm run prisma:generate
# Run database migrations
npm run prisma:migrate
# Seed the database with initial data
npm run prisma:seed# Copy environment template
cp .env.example .env
# Edit .env with your configuration
nano .envnpx playwright installCreate 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"npm run devThe server will start at http://localhost:8888
# 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:seednpm run build
npm start- Development:
http://localhost:8888/api - Production:
https://yourdomain.com/api
All protected routes require:
- JWT Token: Include in
Authorizationheader asBearer <token> - API Key: Include in
x-api-keyheader (value fromX_HEADER_KEY)
POST /api/auth/signup- Register new userPOST /api/auth/login- User loginGET /api/users- Get all users (admin only)GET /api/users/:id- Get user by IDPUT /api/users/:id- Update userDELETE /api/users/:id- Delete user
GET /health- Server health status
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"
}| 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 |
- 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
id: Primary keyemail: Unique email addresspassword: Hashed passwordname: User display namerole: User role (ADMIN/USER)createdAt/updatedAt: Timestamps
- Extended features for Binance integration
- Proxy support configuration
- Authentication state management
- Transaction management and tracking
- Status monitoring and logging
The application includes automated background tasks:
- Cron Scheduling:
feat: configurable task scheduling
For consistent development environment, use Docker:
cd docker-db
docker compose up -dThis sets up MySQL database with proper configuration.
We follow Conventional Commits specification.
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
feat: A new featurefix: A bug fixdocs: Documentation only changesstyle: Changes that do not affect the meaning of the coderefactor: A code change that neither fixes a bug nor adds a featureperf: A code change that improves performancetest: Adding missing tests or correcting existing testsbuild: Changes that affect the build system or external dependenciesci: Changes to our CI configuration files and scriptschore: Other changes that don't modify src or test filesrevert: Reverts a previous commit
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- Fork the repository
- Create a feature branch (
git checkout -b feature/auth-refresh) - Make your changes and follow conventional commits
- Push to the branch (
git push origin feature/auth-refresh) - Open a Pull Request with a clear title following conventional commits
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue in the GitHub repository
- Check the existing documentation
- Review the code comments and examples
- Environment Setup: Configure production environment variables
- Database: Set up production database and update connection string
- Build: Run
npm run buildto compile TypeScript - Security: Change all default secrets and keys
- Monitoring: Set up logging and monitoring
- SSL: Configure HTTPS/SSL certificates
- Process Manager: Use PM2 or similar for process management
- 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