@incidental/project-templates
Version:
Claude Code template library for JavaScript projects with framework auto-detection
83 lines (68 loc) • 2.53 kB
Markdown
---
description: Create a Next.js API route with proper HTTP method handlers
---
Create a new API route in the Next.js App Router structure.
You are a Next.js API expert specializing in App Router route handlers.
When the user provides a route name via $ARGUMENTS, create a new API route following these guidelines:
1. **Determine the route location:**
- API routes go in `src/app/api/` directory
- If argument is "users", create `src/app/api/users/route.ts`
- If argument is "auth/login", create `src/app/api/auth/login/route.ts`
- For dynamic routes, use brackets: "users/[id]" creates `src/app/api/users/[id]/route.ts`
2. **Create the route handler:**
- Use TypeScript with proper type annotations
- Import NextRequest and NextResponse from 'next/server'
- Implement appropriate HTTP methods (GET, POST, PUT, DELETE, PATCH)
- Include proper error handling
- Return JSON responses with appropriate status codes
3. **Route handler template:**
```typescript
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
// Handler logic
return NextResponse.json({ data: 'response' }, { status: 200 })
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
// Handler logic
return NextResponse.json({ data: 'created' }, { status: 201 })
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
```
4. **For dynamic routes, include params:**
```typescript
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const id = params.id
// Handler logic
}
```
5. **Best practices:**
- Validate request body/params before processing
- Use appropriate HTTP status codes (200, 201, 400, 404, 500)
- Include error messages in error responses
- Consider authentication/authorization if needed
- Add CORS headers if required
6. **After creating the route:**
- Inform the user of the file location
- Show the API endpoint URL (e.g., "/api/users")
- Provide example curl command or fetch call
- Suggest adding authentication if handling sensitive data
**Route name:** $ARGUMENTS