Next.js API Routes
Relevant source files
The following files were used as context for generating this wiki page:
Next.js API Routes in the ai-reviwer project serve as the primary interface for external integrations and frontend-to-backend communication. These routes are responsible for handling GitHub Webhooks, managing the GitHub OAuth flow, and providing endpoints for user actions within the web application.
The architecture follows a strict separation of concerns where route handlers act as lightweight entry points that parse input and delegate complex business logic to internal services. This design ensures that the web server remains responsive, particularly for webhooks that must acknowledge requests within a few seconds while heavy lifting is offloaded to background workers.
Sources: README.md:82-89, apps/web/app/api/webhooks/github/route.ts:16-24
Core Architecture and Middleware
All API routes in the apps/web directory are wrapped with a higher-order function called withRouteContext. This middleware provides essential cross-cutting concerns including request tracking, logging, and error handling.
withRouteContext Middleware
The middleware implements three primary responsibilities:
- Request ID Resolution: It ensures every request has a unique
X-Request-Id. It either trusts an incoming header (if safe) or generates a new UUID. - AsyncLocalStorage Scope: It sets up a context scope so downstream services can access the
requestId,method, andpathwithout manual parameter threading. - Global Error Handling: It catches unhandled exceptions and converts them into safe JSON responses using
mapErrorToResponse, preventing the leakage of internal stack traces.
Sources: apps/web/src/server/middleware/with-route-context.ts:1-25, README.md:154-159
Request Lifecycle Flow
The following diagram illustrates the flow of a request through the API route infrastructure:
The project uses performance.now() to track request duration, which is then logged upon completion.
Sources: apps/web/src/server/middleware/with-route-context.ts:54-91
GitHub Webhook Integration
The /api/webhooks/github route is the entry point for all automated review triggers and installation events. It is designed to be highly secure and efficient to meet GitHub's delivery requirements.
Webhook Processing Logic
The route performs the following steps before acknowledging the delivery:
- Payload Validation: Enforces a 25 MB cap on payload size.
- Signature Verification: Uses
verifyGithubSignature(HMAC-SHA256) to ensure the request originated from GitHub. - Idempotency: It upserts every delivery into the
WebhookDeliverytable. If adeliveryIdhas already been processed, it returns a 200/202 status without re-triggering logic. - Job Enqueuing: Once verified, it enqueues a
webhook.processjob viapg-bossand returns a202 Acceptedstatus.
Sources: apps/web/app/api/webhooks/github/route.ts:1-26, README.md:46-52
Webhook Flow Diagram
Authentication Routes
The authentication system leverages GitHub OAuth to manage user sessions and link GitHub installations. These routes interact with the AuthService and manage secure cookies.
Callback Route Processing
The /api/auth/github/callback route handles the return from GitHub's OAuth flow:
- Parameter Extraction: Retrieves the
code,state, and optionalinstallation_id. - CSRF Protection: Compares the
statefrom the query against a secure cookie (consumeStateCookie). - Session Creation: Calls
c.auth.completeSignInand, upon success, issues a JWT session usingsetSessionand theSESSION_SECRET. - Context Injection: Promotes the
userIdandinstallationIdinto theAsyncLocalStoragecontext viasetUserContextfor logging.
Sources: apps/web/app/api/auth/github/callback/route.ts:32-80
API Route Summary Table
| Endpoint | Method | Purpose | Key Dependencies |
|---|---|---|---|
/api/webhooks/github | POST | Receives and validates GitHub events | github, db, jobs |
/api/auth/github/start | GET | Initiates GitHub OAuth flow | AuthService |
/api/auth/github/callback | GET | Completes OAuth and creates session | AuthService, session |
/api/auth/signout | POST | Terminates user session | session |
Sources: apps/web/app/api/webhooks/github/route.ts:36, apps/web/app/api/auth/github/callback/route.ts:30, apps/web/app/onboarding/page.tsx:90
Configuration and Deployment
Next.js API routes are configured to run in the nodejs runtime and are forced to be dynamic to ensure they handle every incoming request fresh.
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
Sources: apps/web/app/api/webhooks/github/route.ts:33-34, apps/web/app/api/auth/github/callback/route.ts:16-17
The project uses output: 'standalone' in next.config.js to optimize the production build, ensuring that only necessary dependencies are included in the final Docker image. Certain packages like pino and @prisma/client are marked as serverExternalPackages due to their use of dynamic imports.
Sources: apps/web/next.config.js:12-29
Conclusion
Next.js API Routes in this project serve as a robust gateway for the AI Code Reviewer. By utilizing standardized middleware for context and error management, and offloading heavy processing to a background worker system, the API maintains high availability and performance even during bursty webhook activity from GitHub.