|
| 1 | +--- |
| 2 | +applyTo: "web/src/app/api/**/*.{ts,js}" |
| 3 | +description: Next.js API route development patterns for the turn-based games platform |
| 4 | +--- |
| 5 | + |
| 6 | +# API Route Instructions |
| 7 | + |
| 8 | +Follow these patterns when creating Next.js API routes: |
| 9 | + |
| 10 | +## File Structure and Naming |
| 11 | + |
| 12 | +- Use Next.js 13+ App Router conventions (`route.ts`) |
| 13 | +- Group related routes by game type: `/api/games/[game-type]/` |
| 14 | +- Use dynamic routes for game instances: `/api/games/[game-type]/[id]/` |
| 15 | +- Include MCP-specific sanitized endpoints: `/api/games/[game-type]/mcp/` |
| 16 | + |
| 17 | +## HTTP Method Handlers |
| 18 | + |
| 19 | +Export named functions for each HTTP method: |
| 20 | + |
| 21 | +```typescript |
| 22 | +import { NextRequest, NextResponse } from 'next/server' |
| 23 | + |
| 24 | +export async function GET() { |
| 25 | + // Handle GET requests |
| 26 | +} |
| 27 | + |
| 28 | +export async function POST(request: NextRequest) { |
| 29 | + // Handle POST requests with body |
| 30 | +} |
| 31 | + |
| 32 | +export async function DELETE(request: NextRequest) { |
| 33 | + // Handle DELETE requests |
| 34 | +} |
| 35 | +``` |
| 36 | + |
| 37 | +## Request/Response Patterns |
| 38 | + |
| 39 | +### Request Handling |
| 40 | +- Always use try-catch blocks for error handling |
| 41 | +- Parse request bodies with `await request.json()` |
| 42 | +- Extract URL parameters from dynamic routes: `{ params }: { params: Promise<{ id: string }> }` |
| 43 | +- Validate required fields and return 400 for missing data |
| 44 | + |
| 45 | +### Response Patterns |
| 46 | +- Use `NextResponse.json()` for all responses |
| 47 | +- Include appropriate HTTP status codes: |
| 48 | + - 200: Success |
| 49 | + - 400: Bad request (validation errors, invalid moves) |
| 50 | + - 404: Resource not found |
| 51 | + - 500: Server errors |
| 52 | +- Return consistent error shapes: `{ error: 'Error message' }` |
| 53 | + |
| 54 | +## Game Integration Patterns |
| 55 | + |
| 56 | +### Game State Management |
| 57 | +- Create game instances at module level: `const ticTacToeGame = new TicTacToeGame()` |
| 58 | +- Use shared game storage functions from `@turn-based-mcp/shared` |
| 59 | +- Always validate moves using game logic before applying |
| 60 | +- Update game history with player moves and timestamps |
| 61 | + |
| 62 | +### Move Processing Flow |
| 63 | +```typescript |
| 64 | +// 1. Validate game exists |
| 65 | +const gameSession = await getGameFromStorage(gameId) |
| 66 | +if (!gameSession) { |
| 67 | + return NextResponse.json({ error: 'Game not found' }, { status: 404 }) |
| 68 | +} |
| 69 | + |
| 70 | +// 2. Validate move |
| 71 | +if (!gameInstance.validateMove(gameSession.gameState, move, playerId)) { |
| 72 | + return NextResponse.json({ error: 'Invalid move' }, { status: 400 }) |
| 73 | +} |
| 74 | + |
| 75 | +// 3. Apply move and update state |
| 76 | +let updatedGameState = gameInstance.applyMove(gameSession.gameState, move, playerId) |
| 77 | + |
| 78 | +// 4. Add to history |
| 79 | +const playerMove = { playerId, move, timestamp: new Date() } |
| 80 | +gameSession.history.push(playerMove) |
| 81 | + |
| 82 | +// 5. Check for game end |
| 83 | +const gameResult = gameInstance.checkGameEnd(updatedGameState) |
| 84 | +if (gameResult) { |
| 85 | + updatedGameState = { ...updatedGameState, status: 'finished', winner: gameResult.winner } |
| 86 | +} |
| 87 | + |
| 88 | +// 6. Save and return |
| 89 | +gameSession.gameState = updatedGameState |
| 90 | +await saveGameToStorage(gameId, gameSession) |
| 91 | +return NextResponse.json(gameSession) |
| 92 | +``` |
| 93 | + |
| 94 | +## Error Handling |
| 95 | + |
| 96 | +- Log errors with `console.error()` before returning responses |
| 97 | +- Handle specific error types (validation, storage, parsing) |
| 98 | +- Return generic error messages to avoid exposing internals |
| 99 | +- Use 500 status for unexpected errors |
| 100 | + |
| 101 | +## Security and Sanitization |
| 102 | + |
| 103 | +### MCP Endpoints |
| 104 | +- Create separate `/mcp/` endpoints for MCP server access |
| 105 | +- Sanitize sensitive data (hide current player choices in RPS) |
| 106 | +- Remove incomplete rounds and private information |
| 107 | +- Validate all inputs from external MCP requests |
| 108 | + |
| 109 | +### General Security |
| 110 | +- Validate all input parameters |
| 111 | +- Sanitize data before storage |
| 112 | +- Use proper TypeScript types for request/response shapes |
| 113 | +- Avoid exposing sensitive game state to clients |
| 114 | + |
| 115 | +## Example Route Structure |
| 116 | + |
| 117 | +```typescript |
| 118 | +import { NextRequest, NextResponse } from 'next/server' |
| 119 | +import { GameClass } from '@turn-based-mcp/shared' |
| 120 | +import { getGame, setGame } from '../../../lib/game-storage' |
| 121 | + |
| 122 | +const gameInstance = new GameClass() |
| 123 | + |
| 124 | +export async function POST(request: NextRequest) { |
| 125 | + try { |
| 126 | + const { playerName, gameId } = await request.json() |
| 127 | + |
| 128 | + const players = [ |
| 129 | + { id: 'player1', name: playerName || 'Player', isAI: false }, |
| 130 | + { id: 'ai', name: 'AI', isAI: true } |
| 131 | + ] |
| 132 | + |
| 133 | + const gameState = gameInstance.getInitialState(players) |
| 134 | + if (gameId) gameState.id = gameId |
| 135 | + |
| 136 | + const gameSession = { |
| 137 | + gameState, |
| 138 | + gameType: 'game-type', |
| 139 | + history: [] |
| 140 | + } |
| 141 | + |
| 142 | + await setGame(gameState.id, gameSession) |
| 143 | + return NextResponse.json(gameSession) |
| 144 | + } catch (error) { |
| 145 | + console.error('Error creating game:', error) |
| 146 | + return NextResponse.json({ error: 'Failed to create game' }, { status: 500 }) |
| 147 | + } |
| 148 | +} |
| 149 | +``` |
0 commit comments