{"id":28193074,"url":"https://github.com/yousifabozid/template-nextjs-backend","last_synced_at":"2026-04-11T05:31:34.850Z","repository":{"id":328561502,"uuid":"1109438060","full_name":"YousifAbozid/template-nextjs-backend","owner":"YousifAbozid","description":"✨ Next.js 16+ API backend template with MongoDB, Zod schemas, and type-safe OpenAPI generation. Features functional architecture with zod-to-openapi and Orval SDK generation. 🚀","archived":false,"fork":false,"pushed_at":"2025-12-14T01:09:15.000Z","size":497,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"source","last_synced_at":"2025-12-15T22:51:46.269Z","etag":null,"topics":["backend-template","eslint","husky","lint-staged","mongodb","mongoose","nextjs-template","nextjs16","openapi3","orval","prettier","react-dom","reactjs","swagger","tailwindcss","type-generation","typescript","zod"],"latest_commit_sha":null,"homepage":"https://template-nextjs-backend.vercel.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/YousifAbozid.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-03T20:01:47.000Z","updated_at":"2025-12-14T01:09:18.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/YousifAbozid/template-nextjs-backend","commit_stats":null,"previous_names":["yousifabozid/template-nextjs-backend"],"tags_count":null,"template":true,"template_full_name":null,"purl":"pkg:github/YousifAbozid/template-nextjs-backend","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousifAbozid%2Ftemplate-nextjs-backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousifAbozid%2Ftemplate-nextjs-backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousifAbozid%2Ftemplate-nextjs-backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousifAbozid%2Ftemplate-nextjs-backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/YousifAbozid","download_url":"https://codeload.github.com/YousifAbozid/template-nextjs-backend/tar.gz/refs/heads/source","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousifAbozid%2Ftemplate-nextjs-backend/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31669598,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-10T17:19:37.612Z","status":"online","status_checked_at":"2026-04-11T02:00:05.776Z","response_time":54,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend-template","eslint","husky","lint-staged","mongodb","mongoose","nextjs-template","nextjs16","openapi3","orval","prettier","react-dom","reactjs","swagger","tailwindcss","type-generation","typescript","zod"],"created_at":"2025-05-16T12:16:28.031Z","updated_at":"2026-04-11T05:31:34.809Z","avatar_url":"https://github.com/YousifAbozid.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🚀 Next.js Backend Template\n\nA production-ready Next.js 16+ API backend template with MongoDB integration, dynamic OpenAPI generation, and automatic type-safe documentation.\n\n## ✨ Features\n\n### 🎯 **Zod-to-OpenAPI System**\n\n- **Functional Architecture**: Pure functions with Zod schemas - no classes or decorators\n- **Type-Safe Validation**: Zod schemas provide runtime validation and type inference\n- **Automatic OpenAPI Generation**: Uses `zod-to-openapi` for spec generation\n- **Co-located Schemas**: Route-centric organization with schemas next to handlers\n- **Zero Configuration**: Works out of the box with automatic route discovery\n- **Live Documentation**: Interactive Swagger UI at `/api/docs`\n- **SDK Generation**: Auto-generated React Query hooks with Orval\n\n### 🗃️ **MongoDB Integration**\n\n- **Mongoose ODM**: Full MongoDB integration with schema validation\n- **Connection Caching**: Optimized for serverless environments\n- **Middleware Pattern**: `withDatabase` wrapper for seamless DB connections\n- **Model Organization**: Clean separation of concerns with organized models\n\n### 🔧 **Developer Experience**\n\n- **Hot Reload**: Watch mode for automatic OpenAPI regeneration\n- **Type Safety**: Full TypeScript support with strict type checking\n- **Route-Centric**: Co-located schemas and endpoints for better maintainability\n- **Modern Stack**: Next.js 16+ App Router with ES modules\n\n## 🚀 Quick Start\n\n### Prerequisites\n\n- Node.js 18+\n- MongoDB Atlas account or local MongoDB instance\n- npm or yarn\n\n### Installation\n\n```bash\n# Clone the template\ngit clone https://github.com/YousifAbozid/template-nextjs-backend.git\ncd template-nextjs-backend\n\n# Install dependencies\nnpm install\n\n# Setup environment\ncp .env.example .env\n# Edit .env with your MongoDB connection string\n\n# Generate API documentation and SDK\nnpm run api:generate\nnpm run api:sdk\n\n# Start development server\nnpm run dev\n```\n\n### Environment Variables\n\n```bash\n# .env\nMONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database\nAPI_TITLE=\"Your API Title\"\nAPI_VERSION=\"1.0.0\"\nAPI_DESCRIPTION=\"Your API Description\"\n```\n\n## 📁 Project Structure\n\n```\napp/\n├── api/                    # 🟢 API Routes (You modify these)\n│   ├── users/\n│   │   ├── route.ts       # API endpoints (GET, POST, etc.)\n│   │   ├── schema.ts      # Zod schemas with OpenAPI metadata\n│   │   └── openapi.ts     # OpenAPI route definitions\n│   ├── health/            # Health check endpoint\n│   ├── docs/              # Swagger UI documentation\n│   └── openapi.json/      # OpenAPI JSON endpoint\n├── lib/                   # Shared utilities and business logic\n│   └── api/\n│       ├── database/      # 🟢 Database connection utilities\n│       ├── middleware/    # 🟢 Route handler wrappers (withDatabase, etc.)\n│       ├── models/        # 🟢 Mongoose models\n│       ├── openapi/       # 🟢 OpenAPI registry and helpers\n│       ├── config.ts      # 🟡 API configuration\n│       └── sdk-mutator.ts # 🟡 SDK fetch configuration\n├── layout.tsx             # Root layout\n└── page.tsx               # Landing page\n\nproxy.ts                   # 🟢 Next.js 16+ global proxy (CORS)\nsdk/\n└── index.ts               # 🔴 Auto-generated SDK (don't edit)\n\nopenapi.json               # 🔴 Auto-generated OpenAPI spec (don't edit)\n```\n\n**Legend**: 🟢 Safe to modify | 🟡 Modify carefully | 🔴 Auto-generated (don't touch)\n\n### Middleware Architecture\n\nThis project uses **two types of middleware**:\n\n1. **Global Proxy** (`proxy.ts` at root) - **New in Next.js 16+**\n   - Next.js edge proxy function that runs **before** all requests\n   - Named `proxy.ts` and exports `proxy()` function (changed from `middleware.ts` in v16)\n   - Handles CORS for all API routes\n   - [Next.js Middleware Docs](https://nextjs.org/docs/app/building-your-application/routing/middleware)\n\n2. **Route Handler Wrappers** (`app/lib/api/middleware/`)\n   - Function wrappers for individual route handlers\n   - Examples: `withDatabase` (ensures DB connection)\n   - Used by wrapping your route handlers\n     **Legend**: 🟢 Safe to modify | 🟡 Modify carefully | 🔴 Auto-generated (don't touch)\n\n## 🎯 Adding New API Routes\n\n### 1. Create Route Structure\n\n```bash\nmkdir app/api/products\ntouch app/api/products/route.ts app/api/products/schema.ts app/api/products/openapi.ts\n```\n\n### 2. Define Zod Schemas (`schema.ts`)\n\n```typescript\nimport { z } from 'zod';\nimport { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';\n\nextendZodWithOpenApi(z);\n\nexport const ProductSchema = z\n  .object({\n    _id: z.string().openapi({ description: 'Product ID' }),\n    name: z\n      .string()\n      .min(1)\n      .openapi({ description: 'Product name', example: 'Laptop' }),\n    price: z\n      .number()\n      .min(0)\n      .openapi({ description: 'Product price', example: 999.99 }),\n    category: z\n      .string()\n      .openapi({ description: 'Category', example: 'Electronics' }),\n    description: z.string().optional().openapi({ description: 'Description' }),\n    createdAt: z.coerce.date(),\n    updatedAt: z.coerce.date(),\n  })\n  .openapi('Product');\n\nexport const CreateProductRequestSchema = z\n  .object({\n    name: z.string().min(1).openapi({ description: 'Product name' }),\n    price: z.number().min(0).openapi({ description: 'Product price' }),\n    category: z.string().openapi({ description: 'Category' }),\n    description: z.string().optional(),\n  })\n  .openapi('CreateProductRequest');\n\nexport const ProductListResponseSchema = z\n  .object({\n    success: z.literal(true),\n    data: z.array(ProductSchema),\n    count: z.number(),\n  })\n  .openapi('ProductListResponse');\n\nexport const ProductResponseSchema = z\n  .object({\n    success: z.literal(true),\n    data: ProductSchema,\n    message: z.string().optional(),\n  })\n  .openapi('ProductResponse');\n\nexport type Product = z.infer\u003ctypeof ProductSchema\u003e;\nexport type CreateProductRequest = z.infer\u003ctypeof CreateProductRequestSchema\u003e;\n```\n\n### 3. Register OpenAPI Routes (`openapi.ts`)\n\n```typescript\nimport { registry, createRouteConfig } from '@/lib/api/openapi';\nimport {\n  CreateProductRequestSchema,\n  ProductListResponseSchema,\n  ProductResponseSchema,\n} from './schema';\n\nregistry.registerPath(\n  createRouteConfig({\n    method: 'get',\n    path: '/api/products',\n    tags: ['Products'],\n    summary: 'Get all products',\n    responses: {\n      200: {\n        description: 'Products retrieved successfully',\n        content: {\n          'application/json': { schema: ProductListResponseSchema },\n        },\n      },\n    },\n  })\n);\n\nregistry.registerPath(\n  createRouteConfig({\n    method: 'post',\n    path: '/api/products',\n    tags: ['Products'],\n    summary: 'Create a new product',\n    request: {\n      body: {\n        content: {\n          'application/json': { schema: CreateProductRequestSchema },\n        },\n      },\n    },\n    responses: {\n      201: {\n        description: 'Product created successfully',\n        content: {\n          'application/json': { schema: ProductResponseSchema },\n        },\n      },\n    },\n  })\n);\n```\n\n### 4. Create Route Handler (`route.ts`)\n\n```typescript\nimport { NextRequest, NextResponse } from 'next/server';\nimport { withDatabase } from '@/lib/api/middleware';\nimport { Product } from '@/lib/api/models';\nimport { CreateProductRequestSchema } from './schema';\nimport './openapi'; // Import to register routes\n\nexport const GET = withDatabase(async () =\u003e {\n  const products = await Product.find().sort({ createdAt: -1 });\n  return NextResponse.json({\n    success: true,\n    data: products,\n    count: products.length,\n  });\n});\n\nexport const POST = withDatabase(async (req: NextRequest) =\u003e {\n  const body = await req.json();\n\n  // Validate with Zod\n  const validationResult = CreateProductRequestSchema.safeParse(body);\n  if (!validationResult.success) {\n    return NextResponse.json(\n      { success: false, error: validationResult.error.issues[0].message },\n      { status: 400 }\n    );\n  }\n\n  const product = new Product(validationResult.data);\n  const savedProduct = await product.save();\n\n  return NextResponse.json(\n    {\n      success: true,\n      data: savedProduct,\n      message: 'Product created successfully',\n    },\n    { status: 201 }\n  );\n});\n```\n\n### 5. Create Database Model (`app/lib/api/models/Product.ts`)\n\n```typescript\nimport mongoose, { Schema, Document } from 'mongoose';\n\nexport interface IProduct extends Document {\n  name: string;\n  price: number;\n  category: string;\n  description?: string;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nconst ProductSchema: Schema\u003cIProduct\u003e = new Schema(\n  {\n    name: { type: String, required: true, trim: true },\n    price: { type: Number, required: true, min: 0 },\n    category: { type: String, required: true, trim: true },\n    description: { type: String, trim: true },\n  },\n  { timestamps: true }\n);\n\nexport const Product =\n  mongoose.models.Product || mongoose.model\u003cIProduct\u003e('Product', ProductSchema);\n```\n\n### 6. Regenerate Documentation\n\n```bash\nnpm run api:generate  # Generate OpenAPI spec\nnpm run api:sdk       # Generate React Query SDK\n```\n\n**Result**: Your new route automatically appears in:\n\n- OpenAPI spec at `/api/openapi.json`\n- Interactive docs at `/api/docs`\n- Generated SDK with React Query hooks in `sdk/index.ts`\n\n## 🔧 Available Scripts\n\n```bash\nnpm run dev              # Start development server\nnpm run build            # Build for production (includes OpenAPI + SDK generation)\nnpm run start            # Start production server\nnpm run api:generate     # Generate OpenAPI spec from route definitions\nnpm run api:sdk          # Generate React Query SDK from OpenAPI spec\nnpm run api:watch        # Watch mode for OpenAPI + SDK regeneration\nnpm run api:dev          # Start dev server + OpenAPI/SDK watching\nnpm run type-check       # TypeScript type checking\nnpm run lint             # ESLint\nnpm run lint:fix         # ESLint with auto-fix\nnpm run format           # Prettier formatting\nnpm run format:check     # Check formatting without writing\nnpm run fix-all          # Run lint:fix + format\nnpm run test             # Run all checks (format:check, lint, type-check)\n```\n\n## 📖 API Documentation\n\nOnce running, access your API documentation:\n\n- **Interactive Docs**: [http://localhost:3000/api/docs](http://localhost:3000/api/docs)\n- **OpenAPI Spec**: [http://localhost:3000/api/openapi.json](http://localhost:3000/api/openapi.json)\n- **Health Check**: [http://localhost:3000/api/health](http://localhost:3000/api/health)\n\n## 🔄 Auto-Generation Workflow\n\nThe system automatically:\n\n1. **Scans OpenAPI Files**: Finds all `app/api/**/openapi.ts` files\n2. **Imports Route Definitions**: Loads registry entries from each file\n3. **Generates OpenAPI Spec**: Creates `openapi.json` in project root\n4. **Generates SDK**: Uses Orval to create React Query hooks in `sdk/index.ts`\n5. **Type Safety**: Full TypeScript types inferred from Zod schemas\n\n### Generated Files (Auto-updated)\n\n- `openapi.json` - OpenAPI 3.0 specification (project root)\n- `sdk/index.ts` - Type-safe React Query hooks for API consumption\n\n**⚠️ Never edit these files manually - they're regenerated on every build**\n\n## 🛠️ Tech Stack\n\n- **Framework**: [Next.js 16+](https://nextjs.org/) (App Router)\n- **Language**: TypeScript with ES Modules\n- **Database**: [MongoDB](https://www.mongodb.com/) with [Mongoose](https://mongoosejs.com/)\n- **Validation**: [Zod](https://zod.dev/) - TypeScript-first schema validation\n- **OpenAPI**: [zod-to-openapi](https://github.com/asteasolutions/zod-to-openapi) - Generate OpenAPI from Zod schemas\n- **SDK Generation**: [Orval](https://orval.dev/) - Generate React Query hooks from OpenAPI\n- **Documentation**: [Swagger UI](https://swagger.io/tools/swagger-ui/) - Interactive API documentation\n- **Code Quality**: [ESLint](https://eslint.org/) + [Prettier](https://prettier.io/) + [TypeScript](https://www.typescriptlang.org/)\n- **Development**: [Chokidar](https://github.com/paulmillr/chokidar) file watching + [Concurrently](https://github.com/open-cli-tools/concurrently)\n- **Development**: [Chokidar](https://github.com/paulmillr/chokidar) file watching + [Concurrently](https://github.com/open-cli-tools/concurrently)\n\n## 🚀 Deployment\n\n### Vercel (Recommended)\n\n```bash\n# Install Vercel CLI\nnpm i -g vercel\n\n# Deploy\nvercel --prod\n```\n\n### Docker\n\n```bash\n# Build image\ndocker build -t nextjs-backend .\n\n# Run container\ndocker run -p 3000:3000 nextjs-backend\n```\n\n### Manual Deployment\n\n```bash\n# Build for production\nnpm run build\n\n# Start production server\nnpm start\n```\n\n## 📚 Additional Resources\n\n- **[Development Guide](app/DEVELOPMENT_GUIDE.md)** - Comprehensive development documentation\n- **[Middleware Guide](MIDDLEWARE_GUIDE.md)** - Complete guide to global vs route-specific middleware\n- **[SDK Usage Examples](SDK_USAGE_EXAMPLES.md)** - How to use the auto-generated SDK\n- **[GitHub Copilot Instructions](.github/copilot-instructions.md)** - AI coding assistant setup\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🙏 Acknowledgments\n\n- [Next.js](https://nextjs.org/) team for the amazing framework\n- [Mongoose](https://mongoosejs.com/) for MongoDB integration\n- [OpenAPI](https://www.openapis.org/) specification contributors\n- [Swagger](https://swagger.io/) for API documentation tools\n\n---\n\n**Built with ❤️ by [Yousif Abozid](https://github.com/YousifAbozid)**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyousifabozid%2Ftemplate-nextjs-backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyousifabozid%2Ftemplate-nextjs-backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyousifabozid%2Ftemplate-nextjs-backend/lists"}