nextjs-api
Skill0 starsChanged 4 months agoMITView on GitHub
Patterns for building API routes in Next.js App Router.
- Reads credentials
In this repository37 other files it gives its agents.
- .agents/skills/vercel-composition-patterns/AGENTS.mdAGENTS.md
- vercel-composition-patterns/AGENTS.mdAGENTS.md
- senior-frontendSkill
- vercel-composition-patternsSkill
- bento-designSkill
- fanned-cardsSkill
- flip-cardSkill
- floating-quotesSkill
- githubSkill
- glassmorphism-uiSkill
- gmail-proxySkill
- googleSkill
- hippocampusSkill
- html-pdf-exportSkill
- iframe-previewSkill
- infinite-canvasSkill
- matrix-textSkill
- nextjs-expertSkill
- pinterestSkill
- railway-deploySkill
- remotion-videoSkill
- scramble-textSkill
- scroll-video-heroSkill
- senior-frontendSkill
- SEOSkill
- ship-websiteSkill
- sound-engineSkill
- stripe-best-practicesSkill
- tilt-cardSkill
- tube-summarySkill
- upload-postSkill
- vercel-composition-patternsSkill
- vercel-deploySkill
- vercel-react-best-practicesSkill
- vertical-fanned-cardsSkill
- video-contentSkill
- war-roomSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 2 are distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 242
Always validate input: - use Zod or similar
- Distinctive: line 246
Log errors server-side: - don't expose details to clients
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Next.js API Skill
Patterns for building API routes in Next.js App Router.
When to Use
- Building REST APIs in Next.js
- Backend logic for your frontend
- Proxy APIs to external services
Route Structure
app/
├── api/
│ ├── items/
│ │ ├── route.ts # GET /api/items, POST /api/items
│ │ └── [id]/
│ │ ├── route.ts # GET/PUT/DELETE /api/items/:id
│ │ └── action/
│ │ └── route.ts # POST /api/items/:id/action
│ └── health/
│ └── route.ts # GET /api/healthBasic CRUD
// app/api/items/route.ts
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const limit = parseInt(searchParams.get('limit') || '10');
const items = await db.items.findMany({ take: limit });
return NextResponse.json({ items });
}
export async function POST(request: Request) {
const body = await request.json();
// Validate
if (!body.title) {
return NextResponse.json(
{ error: 'title required' },
{ status: 400 }
);
}
const item = await db.items.create({ data: body });
return NextResponse.json({ item }, { status: 201 });
}// app/api/items/[id]/route.ts
import { NextResponse } from 'next/server';
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
const item = await db.items.findUnique({ where: { id: params.id } });
if (!item) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ item });
}
export async function PUT(
request: Request,
{ params }: { params: { id: string } }
) {
const body = await request.json();
const item = await db.items.update({
where: { id: params.id },
data: body,
});
return NextResponse.json({ item });
}
export async function DELETE(
request: Request,
{ params }: { params: { id: string } }
) {
await db.items.delete({ where: { id: params.id } });
return NextResponse.json({ success: true });
}API Key Authentication
// lib/auth.ts
export function validateApiKey(request: Request): boolean {
const apiKey = request.headers.get('x-api-key')
|| new URL(request.url).searchParams.get('key');
return apiKey === process.env.API_KEY;
}
// Middleware wrapper
export function withAuth(handler: Function) {
return async (request: Request, context: any) => {
if (!validateApiKey(request)) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return handler(request, context);
};
}
// Usage
export const GET = withAuth(async (request: Request) => {
// Protected logic
});Error Handling
// lib/api-utils.ts
export function apiError(message: string, status: number = 400) {
return NextResponse.json({ error: message }, { status });
}
export function apiSuccess<T>(data: T, status: number = 200) {
return NextResponse.json(data, { status });
}
export async function withErrorHandling(
handler: () => Promise<NextResponse>
) {
try {
return await handler();
} catch (error) {
console.error('API Error:', error);
return apiError('Internal server error', 500);
}
}
// Usage
export async function POST(request: Request) {
return withErrorHandling(async () => {
const body = await request.json();
const item = await db.items.create({ data: body });
return apiSuccess({ item }, 201);
});
}Validation with Zod
import { z } from 'zod';
const createItemSchema = z.object({
title: z.string().min(1).max(200),
type: z.enum(['note', 'link', 'image']),
content: z.string().optional(),
url: z.string().url().optional(),
});
export async function POST(request: Request) {
const body = await request.json();
const result = createItemSchema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{ error: 'Validation failed', details: result.error.issues },
{ status: 400 }
);
}
const item = await db.items.create({ data: result.data });
return NextResponse.json({ item }, { status: 201 });
}CORS Headers
// For APIs called from other origins
export async function GET(request: Request) {
const response = NextResponse.json({ data: 'hello' });
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, X-Api-Key');
return response;
}
// Handle preflight
export async function OPTIONS(request: Request) {
return new NextResponse(null, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, X-Api-Key',
},
});
}Rate Limiting
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '10 s'), // 10 requests per 10 seconds
});
export async function POST(request: Request) {
const ip = request.headers.get('x-forwarded-for') || 'anonymous';
const { success, limit, remaining } = await ratelimit.limit(ip);
if (!success) {
return NextResponse.json(
{ error: 'Rate limit exceeded' },
{
status: 429,
headers: {
'X-RateLimit-Limit': limit.toString(),
'X-RateLimit-Remaining': remaining.toString(),
}
}
);
}
// Process request...
}Best Practices
- Always validate input - use Zod or similar
- Return consistent response shapes -
{ data }or{ error } - Use proper HTTP status codes - 201 for created, 404 for not found, etc.
- Add rate limiting - protect against abuse
- Log errors server-side - don't expose details to clients
- Use middleware for auth - DRY principle
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

