The Backend Bible - Fastify, TypeScript & MongoDB
No description provided.
$ npx @airuleshub/cli@latest add the-backend-bible-fastify-typescript-mongodbRule Content
Fastify + TypeScript + MongoDB Backend - Project Initialization Guide
AI Instruction: Use this document to fully scaffold and initialize the backend project. Follow each section in order. Do not skip steps. Generate all files with the exact structure and content described.
Tech Stack
Folder Structure
Generate the following folder and file structure exactly:
Step 1 — Initialize the Project
Run the following commands:
Step 2 — Install Dependencies
Step 3 — TypeScript Configuration
File: tsconfig.json
Step 4 — Package.json Scripts
Add the following scripts block to package.json:
Step 5 — Environment Variables
File: .env.example
File: .env — copy from .env.example and fill in real values.
Step 6 — Zod Environment Validation
File: src/config/env.ts
Step 7 — MongoDB Connection
File: src/config/db.ts
Step 8 — Fastify App Factory
File: src/app.ts
Step 9 — Server Entry Point
File: src/server.ts
Step 10 — Example Module
Zod Schema
File: src/modules/example/example.schema.ts
Mongoose Model
File: src/modules/example/example.model.ts
Service Layer
File: src/modules/example/example.service.ts
Controller
File: src/modules/example/example.controller.ts
Route Registration
File: src/modules/example/example.route.ts
Note: Install
zod-to-json-schemawith:npm install zod-to-json-schema
Step 11 — Utility Helpers
File: src/utils/response.ts
Step 12 — ESLint & Prettier Config
File: .eslintrc.json
File: .prettierrc
Step 13 — .gitignore
File: .gitignore
Conventions & Patterns
Adding a New Module
To add a new module (e.g., user), create the following files following the same pattern:
Then register the route in src/app.ts:
Validation Pattern
Always validate input using Zod schemas in the schema file. Pass type-safe inferred types to controllers and services. Never bypass Zod for request body or params.
Error Handling
Use reply.notFound(), reply.badRequest(), and reply.internalServerError() from @fastify/sensible. Wrap async service calls in try/catch at the controller level for unexpected errors.
API Endpoints (Example Module)
Final Checklist for AI Initialization
- Run
npm installafter generatingpackage.json - Create
.envfrom.env.examplewith real values - Ensure MongoDB is running locally or provide Atlas URI
- Run
npm run devto verify the server starts - Hit
GET /healthto confirm the app is live - Check MongoDB connection log for
✅ MongoDB connected
