Skip to content

About

A modern, fast and modular backend template built with Bun, TypeScript, Prisma ORM and Fastify, structured around Clean Architecture principles. This repo is intended as a production-ready starting point for APIs that need good separation of concerns, strong typing and fast startup.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Repository files navigation

BunTs-Prisma-Server

A modern, fast and modular backend template built with Bun, TypeScript, Prisma ORM and Fastify, structured around Clean Architecture principles.
This repo is intended as a production-ready starting point for APIs that need good separation of concerns, strong typing and fast startup.


Key Features

  • ⚡ Bun runtime for super-fast startup & execution
  • 🚀 Fastify HTTP server (high-performance)
  • 🗄 Prisma ORM for type-safe database access and migrations
  • 🏛 Clean Architecture (clear separation: presentation, application, domain, infrastructure)
  • ✅ TypeScript-first codebase for developer ergonomics and safety
  • 📄 Swagger UI (/docs) auto-generated for API exploration
  • 🔁 Database seed script & Prisma migrations ready

Table of Contents


Quickstart

# 1. install dependencies
bun install

# 2. generate Prisma client (after setting DATABASE_URL)
bunx prisma generate

# 3. run migrations (development)
bunx prisma migrate dev --name init

# or for production deployments
bunx prisma migrate deploy

# 4. start the server (development)
bun run dev

# Server defaults to PORT (env) or 9202 and exposes swagger at /docs

Prerequisites

  • Bun (recommended v1.x / latest stable) — https://bun.sh
  • Node-compatible environment for local tools (you mainly use Bun)
  • PostgreSQL (or whatever your DATABASE_URL target is per prisma/schema.prisma)
  • Optional: MailTrap credentials if using the included email sender utils

Environment variables

Create a .env in the project root (example):

# Server
PORT=9202
SWAGGER_AVAILABLE=true

# Database (Prisma)
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"

# JWT / tokens
ACCESS_TOKEN_EXPIRATION=3600
REFRESH_TOKEN_EXPIRATION=2592000

# Seed creds (optional)
USER_NAME_SEED=admin@example.com
PASSWORD_SEED=supersecret

# Email (Mailtrap example)
MAILTRAP_API_TOKEN=your-mailtrap-token
MAILTRAP_INBOX_ID=your-mailtrap-inbox-id

Note: The project contains PEM key files under src/shared/constants/key/ (public/private) used in JWT or crypto utilities. For production, prefer storing secrets in a secure store or environment variables, and rotate keys when necessary.


Database & Prisma

Prisma datasource is configured in prisma/schema.prisma and expects DATABASE_URL environment variable.

Common commands:

# generate prisma client
bunx prisma generate

# create/migrate DB (dev)
bunx prisma migrate dev --name <migration-name>

# apply migrations (CI/production)
bunx prisma migrate deploy

# open prisma studio
bunx prisma studio

Migrations are located in prisma/migrations/. Check them into version control.


Project structure

src/
├── app.ts                      # Fastify app configuration (plugins, middleware)
├── server.ts                   # App bootstrap + Prisma connection + listen
├── routes/                     # Route collection & registration
├── modules/                    # Feature modules (users, products, prices, etc.)
│   ├── users/
│   ├── products/
│   ├── prices/
│   └── ...
├── shared/
│   ├── config/                  # prisma instance, config helpers
│   ├── constants/               # keys, constants, static files
│   ├── doc/                     # swagger setup
│   └── errors/                  # custom error types
├── utils/                       # helpers (emailSender, jwt, validators)
└── seed/                        # seed script (src/seed/seed.ts)
prisma/
├── schema.prisma
└── migrations/
package.json
tsconfig.json
README.md

Modules present in this project (examples): admins, categories, currency, prices, products, reports, userAsset, userVerifications, users, lists, listItems, options, footers.


Scripts (from package.json)

# Run the server in dev (using bun)
bun run dev

# Run tests (Vitest)
bun run test
bun run test:watch

# Run seed script
bun run seed

# Lint & format
bun run lint
bun run format

Note: The repository's seed script currently runs with sudo in package.json ("seed": "sudo bun run src/seed/seed.ts"). Remove sudo if not required by your environment — running seeds as root is generally discouraged.


Architecture overview

This project follows Clean Architecture concepts:

  • Presentation (routes, controllers) — HTTP layer (Fastify) that receives requests and returns responses.
  • Application (modules/*/*.service.ts, use-cases) — orchestrates business rules and application workflows.
  • Domain (entities & types) — core types and domain contracts.
  • Infrastructure (shared/config/instances/prisma.instance.ts, repositories) — database & external integrations (Prisma, email, file storage).

Benefits:

  • Easier to test business logic without HTTP or DB dependencies.
  • Swappable infrastructure (e.g., change Prisma to another ORM) without changing business rules.
  • Clear responsibilities and scalable code organization for large teams.

Seeding data

Run the seed script to populate initial data (admins, roles, sample records):

# ensure DB & prisma client are prepared
bunx prisma generate
bunx prisma migrate dev --name seed-ready

# run seed
bun run seed

If seed requires special permissions, adjust the script instead of running with sudo.


Testing & linting

  • Unit tests use Vitest (bun run test)
  • Linting with ESLint and formatting with Prettier:
bun run lint
bun run format

Swagger / API docs

The app registers Swagger and Swagger-UI in src/shared/doc/swagger.ts. Once the server runs, docs are available at:

http://localhost:<PORT>/docs

This is convenient for inspecting routes and trying endpoints in development.


Development notes & recommendations

  • Keep Prisma schema and migration history in sync; run prisma generate after schema changes.
  • Prefer env-based secrets for production (do not commit private keys or secrets). The repo contains example PEM keys under src/shared/constants/key/ — replace those in production.
  • Use a process manager or container orchestrator (Docker / Kubernetes) for production deployments. For containerized builds, ensure Bun is available in the image or use node build alternatives.
  • Add CI checks (lint + test + prisma migrate status) to PR pipelines.

Contributing

Contributions are welcome. Suggested workflow:

  1. Fork the repo and create a feature branch: feat/<short-description>
  2. Add tests for new logic (Vitest)
  3. Run bun run lint and bun run format before push
  4. Open a PR with a clear summary and testing steps

If you want, I can help prepare:

  • a CONTRIBUTING.md
  • PR / issue templates
  • CI workflow (GitHub Actions) for lint/test/migrate

Roadmap (suggested)

  • Add comprehensive unit & integration tests for modules (users, products, prices)
  • Add Dockerfile + docker-compose for local dev
  • Add CI pipeline to run migrations & tests on PRs
  • Improve auth with refresh token rotation & secure cookie usage
  • Add observability: logging, metrics, and structured error tracking

About

A modern, fast and modular backend template built with Bun, TypeScript, Prisma ORM and Fastify, structured around Clean Architecture principles. This repo is intended as a production-ready starting point for APIs that need good separation of concerns, strong typing and fast startup.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages