|
| 1 | +--- |
| 2 | +name: backend-fastify |
| 3 | +description: Backend development using Fastify + TypeScript. Use when creating new backend APIs, adding routes, implementing services, working with plugins, or configuring environment variables. |
| 4 | +--- |
| 5 | + |
| 6 | +# Backend Fastify Stack |
| 7 | + |
| 8 | +High-performance Node.js backend stack: |
| 9 | + |
| 10 | +- **Fastify 5.x** - Web framework |
| 11 | +- **TypeScript** - Type safety |
| 12 | +- **tsx** - Development with watch mode |
| 13 | +- **pino-pretty** - Pretty logging for development |
| 14 | +- **@fastify/env** - Environment variable validation with JSON Schema |
| 15 | +- **@fastify/cors** - CORS support |
| 16 | +- **fastify-plugin** - Plugin system |
| 17 | + |
| 18 | +## Environment Setup |
| 19 | + |
| 20 | +Use [asdf](https://asdf-vm.com/) to manage Node.js versions: |
| 21 | + |
| 22 | +```bash |
| 23 | +# Install Node.js plugin (one-time) |
| 24 | +asdf plugin add nodejs |
| 25 | + |
| 26 | +# Set project Node.js version |
| 27 | +asdf set nodejs latest:22 |
| 28 | +``` |
| 29 | + |
| 30 | +This creates a `.tool-versions` file in the project root that ensures consistent Node.js versions across the team. |
| 31 | + |
| 32 | +## Reference Files |
| 33 | + |
| 34 | +| File | When to Use | |
| 35 | +|------|-------------| |
| 36 | +| [setup-guide.md](references/setup-guide.md) | Starting a new backend project from scratch | |
| 37 | +| [patterns.md](references/patterns.md) | Implementing routes, services, schema validation | |
| 38 | +| [authentication.md](references/authentication.md) | Adding JWT auth, authorization, protected routes | |
| 39 | +| [api-design.md](references/api-design.md) | Swagger/OpenAPI integration, response format, errors | |
| 40 | +| [mcp-integration.md](references/mcp-integration.md) | Integrating MCP server for AI agent access | |
| 41 | +| [gotchas.md](references/gotchas.md) | Debugging issues, common mistakes and fixes | |
| 42 | + |
| 43 | +## Quick Reference |
| 44 | + |
| 45 | +### Commands |
| 46 | + |
| 47 | +```bash |
| 48 | +# Dev server with watch mode |
| 49 | +npm run dev |
| 50 | + |
| 51 | +# Build for production |
| 52 | +npm run build |
| 53 | + |
| 54 | +# Run production build |
| 55 | +npm start |
| 56 | + |
| 57 | +# Type check |
| 58 | +npm run type-check |
| 59 | +``` |
| 60 | + |
| 61 | +### Key Imports |
| 62 | + |
| 63 | +```typescript |
| 64 | +// Fastify types |
| 65 | +import Fastify, { FastifyInstance, FastifyPluginAsync } from 'fastify' |
| 66 | +import fp from 'fastify-plugin' |
| 67 | + |
| 68 | +// Common plugins |
| 69 | +import fastifyEnv from '@fastify/env' |
| 70 | +import cors from '@fastify/cors' |
| 71 | +``` |
| 72 | + |
| 73 | +### Configuration Access |
| 74 | + |
| 75 | +Always access configuration through `fastify.config`, never `process.env` directly: |
| 76 | + |
| 77 | +```typescript |
| 78 | +// CORRECT - type-safe, validated at startup |
| 79 | +const port = fastify.config.PORT |
| 80 | +const apiKey = fastify.config.API_KEY |
| 81 | + |
| 82 | +// WRONG - no validation, no type safety |
| 83 | +const port = process.env.PORT // Don't do this |
| 84 | +``` |
| 85 | + |
| 86 | +### Response Format |
| 87 | + |
| 88 | +```typescript |
| 89 | +// Standard response structure |
| 90 | +{ |
| 91 | + success: boolean |
| 92 | + data?: T |
| 93 | + error?: string |
| 94 | + metadata?: { timestamp: Date } |
| 95 | +} |
| 96 | +``` |
| 97 | + |
| 98 | +### Plugin Pattern |
| 99 | + |
| 100 | +```typescript |
| 101 | +import fp from 'fastify-plugin' |
| 102 | + |
| 103 | +export default fp(async (fastify, opts) => { |
| 104 | + // Plugin logic here |
| 105 | + fastify.decorate('something', value) |
| 106 | +}, '5.x') |
| 107 | +``` |
| 108 | + |
| 109 | +### Route Pattern |
| 110 | + |
| 111 | +```typescript |
| 112 | +import { FastifyPluginAsync } from 'fastify' |
| 113 | + |
| 114 | +const routes: FastifyPluginAsync = async (fastify, opts) => { |
| 115 | + fastify.get('/', async (request, reply) => { |
| 116 | + return { success: true, data: 'example' } |
| 117 | + }) |
| 118 | +} |
| 119 | + |
| 120 | +export default routes |
| 121 | +``` |
| 122 | + |
| 123 | +### Service Pattern |
| 124 | + |
| 125 | +```typescript |
| 126 | +// 1. Create service class |
| 127 | +export class MyService { |
| 128 | + constructor(private fastify: FastifyInstance) {} |
| 129 | + |
| 130 | + async doWork() { |
| 131 | + // Access config through fastify instance |
| 132 | + const apiKey = this.fastify.config.API_KEY |
| 133 | + this.fastify.log.info('Service method called') |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +// 2. Declare module augmentation |
| 138 | +declare module 'fastify' { |
| 139 | + interface FastifyInstance { |
| 140 | + myService: MyService |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +// 3. Initialize and decorate in app.ts |
| 145 | +fastify.decorate('myService', new MyService(fastify)) |
| 146 | +``` |
| 147 | + |
| 148 | +### Project Structure |
| 149 | + |
| 150 | +``` |
| 151 | +backend/ |
| 152 | +├── src/ |
| 153 | +│ ├── plugins/ # Fastify plugins (env, auth, etc.) |
| 154 | +│ ├── routes/ # HTTP route handlers |
| 155 | +│ ├── services/ # Business logic classes |
| 156 | +│ ├── utils/ # Shared utilities |
| 157 | +│ ├── app.ts # Plugin registration & setup |
| 158 | +│ └── index.ts # Server entry point |
| 159 | +├── package.json |
| 160 | +├── tsconfig.json |
| 161 | +├── .env.example |
| 162 | +└── .gitignore |
| 163 | +``` |
| 164 | + |
| 165 | +### Common Gotchas |
| 166 | + |
| 167 | +- **Plugin order matters**: Register env plugin first, then services, then routes |
| 168 | +- **Config access**: Use `fastify.config.VAR` not `process.env.VAR` |
| 169 | +- **Server ready**: Call `await server.ready()` before accessing config in index.ts |
| 170 | +- **Path normalization**: Centralize path utilities, handle root '/' as special case |
| 171 | +- **Package management**: Use `npm install <pkg>` not manual `package.json` edits |
0 commit comments