nextjs-api-route-standards.mdc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
---globs: - "app/api/**/*.ts" - "app/**/route.ts"alwaysApply: false--- ## API Route Conventions ### Error Handling Always wrap API handlers in try-catch and return proper HTTP status codes: ```typescriptexport async function GET(request: Request) { try { const data = await fetchData(); return Response.json(data); } catch (error) { console.error("API Error:", error); return Response.json( { error: "Internal server error" }, { status: 500 } ); }}``` ### Authentication Check Always verify authentication at the start of protected routes: ```typescriptexport async function POST(request: Request) { const session = await getServerSession(); if (!session) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } // ... rest of handler}``` ### Input Validation Use Zod for request body validation: ```typescriptconst CreateUserSchema = z.object({ email: z.string().email(), name: z.string().min(2),}); export async function POST(request: Request) { const body = await request.json(); const result = CreateUserSchema.safeParse(body); if (!result.success) { return Response.json({ error: result.error }, { status: 400 }); } // ... use result.data}```
MDC (Frontmatter)Markdown