bunjs
Use when building Bun.js/Hono applications, implementing HTTP endpoints, setting up Prisma/SQLite, writing Zod validation, or using Bun's test runner. See bunjs-architecture for layered patterns, bunjs-production for deployment.
What this skill does
# Bun.js Backend Patterns
## Overview
Bun runtime patterns for building fast TypeScript backend services. This skill covers core Bun features, HTTP servers with Hono, database access with Prisma, validation with Zod, error handling, testing, and configuration patterns.
**When to use this skill:**
- Implementing basic HTTP endpoints and route handlers
- Setting up middleware patterns (CORS, logging, auth)
- Working with SQLite or PostgreSQL databases
- Implementing request validation with Zod
- Writing tests with Bun's native test runner
- Basic file operations and WebSocket handling
**For advanced topics, see:**
- **dev:bunjs-architecture** - Layered architecture, clean code patterns, camelCase conventions
- **dev:bunjs-production** - Docker, AWS, Redis caching, security, CI/CD
- **dev:bunjs-apidog** - OpenAPI specs and Apidog integration
## Why Bun
Bun fundamentally transforms TypeScript backend development by:
- **Native TypeScript execution** - No build steps in development
- **Lightning-fast performance** - 3-4x faster than Node.js for many operations
- **Unified toolkit** - Built-in test runner, bundler, and transpiler
- **Drop-in compatibility** - Most Node.js APIs and npm packages work
- **Developer experience** - Hot reload with `--hot`, instant feedback
## Stack Overview
- **Bun 1.x** (runtime, package manager, test runner, bundler)
- **TypeScript 5.7** (strict mode)
- **Hono 4.6** (ultra-fast web framework, TypeScript-first)
- **Prisma 6.2** (type-safe ORM)
- **Biome 2.3** (formatting + linting, replaces ESLint + Prettier)
- **Zod** (runtime validation)
- **PostgreSQL 17 / SQLite** (database)
## Project Structure
```
project-root/
├── src/
│ ├── server.ts # Entry point (starts server)
│ ├── app.ts # Hono app initialization & middleware
│ ├── config.ts # Environment configuration
│ ├── core/ # Core utilities (errors, logger, responses)
│ ├── database/
│ │ ├── client.ts # Prisma client setup
│ │ └── repositories/ # Data access layer (Prisma queries)
│ ├── services/ # Business logic layer
│ ├── controllers/ # HTTP handlers (calls services)
│ ├── middleware/ # Hono middleware (auth, validation, etc.)
│ ├── routes/ # API route definitions
│ ├── schemas/ # Zod validation schemas
│ ├── types/ # TypeScript type definitions
│ └── utils/ # Utility functions
├── tests/
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests (API + DB)
├── prisma/ # Prisma schema & migrations
├── tsconfig.json # TypeScript config
├── biome.json # Biome config
├── package.json # Bun-managed dependencies
└── bun.lockb # Bun lockfile
```
**Key Principles:**
- Structure by **technical capability**, not by feature
- Each layer has **single responsibility**
- No HTTP handling in services, no business logic in controllers
- Easy to test components in isolation
## Quick Start
```bash
# Initialize project
bun init
# Install dependencies
bun add hono @hono/node-server zod @prisma/client bcrypt jsonwebtoken
bun add -d @types/node @types/jsonwebtoken @types/bcrypt typescript prisma @biomejs/biome @types/bun
# Initialize tools
bunx tsc --init
bunx prisma init
bunx @biomejs/biome init
```
**package.json scripts:**
```json
{
"scripts": {
"dev": "bun --hot src/server.ts",
"start": "NODE_ENV=production bun src/server.ts",
"build": "bun build src/server.ts --target bun --outdir dist",
"test": "bun test",
"test:watch": "bun test --watch",
"lint": "biome lint --write",
"format": "biome format --write",
"check": "biome check --write",
"typecheck": "tsc --noEmit",
"db:generate": "prisma generate",
"db:migrate": "prisma migrate dev",
"db:studio": "prisma studio"
}
}
```
## TypeScript Configuration
**tsconfig.json (key settings):**
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022"],
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"types": ["bun-types"],
"baseUrl": ".",
"paths": {
"@core/*": ["src/core/*"],
"@database/*": ["src/database/*"],
"@services/*": ["src/services/*"],
"@/*": ["src/*"]
}
}
}
```
**Critical settings:**
- `"strict": true` - Enable all strict checks
- `"moduleResolution": "bundler"` - Aligns with Bun's resolver
- Use `paths` for clean imports (`@core/*`, `@services/*`)
## HTTP Server with Hono
### Basic Server Setup
**Entry point (src/server.ts):**
```typescript
import { serve } from '@hono/node-server';
import { app } from './app';
const PORT = Number(process.env.PORT) || 3000;
serve({ fetch: app.fetch, port: PORT });
console.log(`🚀 Server running on port ${PORT}`);
```
**App initialization (src/app.ts):**
```typescript
import { Hono } from 'hono';
import { logger } from 'hono/logger';
import { cors } from 'hono/cors';
import userRouter from './routes/user.routes';
export const app = new Hono();
// Global middleware
app.use('*', logger());
app.use('*', cors({
origin: ['http://localhost:3000'],
allowHeaders: ['Content-Type', 'Authorization'],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
credentials: true
}));
// Health check
app.get('/health', (c) => c.json({ status: 'ok' }));
// API routes
app.route('/api/users', userRouter);
```
### Route Handlers
**Routes (src/routes/user.routes.ts):**
```typescript
import { Hono } from 'hono';
import * as userController from '../controllers/user.controller';
import { validate } from '../middleware/validator';
import { createUserSchema } from '../schemas/user.schema';
const userRouter = new Hono();
userRouter.get('/', userController.getUsers);
userRouter.get('/:id', userController.getUserById);
userRouter.post('/', validate(createUserSchema), userController.createUser);
userRouter.put('/:id', userController.updateUser);
userRouter.delete('/:id', userController.deleteUser);
export default userRouter;
```
**Controllers (src/controllers/user.controller.ts):**
```typescript
import type { Context } from 'hono';
import * as userService from '../services/user.service';
export const createUser = async (c: Context) => {
const data = c.get('validatedData');
const user = await userService.createUser(data);
return c.json(user, 201);
};
export const getUserById = async (c: Context) => {
const id = c.req.param('id');
const user = await userService.getUserById(id);
return c.json(user);
};
export const getUsers = async (c: Context) => {
const page = Number(c.req.query('page')) || 1;
const limit = Number(c.req.query('limit')) || 20;
const result = await userService.getUsers({ page, limit });
return c.json(result);
};
export const updateUser = async (c: Context) => {
const id = c.req.param('id');
const data = await c.req.json();
const user = await userService.updateUser(id, data);
return c.json(user);
};
export const deleteUser = async (c: Context) => {
const id = c.req.param('id');
await userService.deleteUser(id);
return c.json({ message: 'User deleted' });
};
```
## Middleware Patterns
### Validation Middleware
**src/middleware/validator.ts:**
```typescript
import { z, ZodSchema } from 'zod';
import type { Context, Next } from 'hono';
export const validate = (schema: ZodSchema) => async (c: Context, next: Next) => {
try {
const body = await c.req.json();
c.set('validatedData', schema.parse(body));
await next();
} catch (e) {
if (e instanceof z.ZodError) {
return c.json({ error: 'Validation failed', details: e.issues }, 422);
}
throw e;
Related in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.