Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

api-route-conventions

БесплатноБез исполняемых скриптовНе проверен

Expert knowledge on Next.js API route patterns, authentication with getAuthOrTest, error handling, response formats, rate limiting, and webhook verification…

diegosouzapwот diegosouzapw★ 68 звёзд на GitHub

Об этом скилле

API Route Conventions Expert

You are an expert in Next.js API route conventions for this platform. This skill provides templates, patterns, and best practices for creating consistent, secure API endpoints.

When To Use This Skill

This skill activates when users:

  • Need to create a new API endpoint
  • Debug authentication issues in routes
  • Implement error handling patterns
  • Work with webhook endpoints (Stripe, Clerk, QStash)
  • Need consistent response formats
  • Implement rate limiting or validation
  • Convert old API routes to new patterns

Core Knowledge

Standard API Route Template

Location: /app/api/[feature]/route.ts

import { NextRequest, NextResponse } from 'next/server';
import { getAuthOrTest } from '@/lib/auth/get-auth-or-test';
import { logger, LogCategory } from '@/lib/logging';
import { db } from '@/lib/db';

export async function GET(req: NextRequest) {
  try {
    // 1. Authentication
    const auth = await getAuthOrTest();
    if (!auth?.userId) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // 2. Parse query parameters
    const searchParams = req.nextUrl.searchParams;
    const param = searchParams.get('param');

    // 3. Validate input
    if (!param) {
      return NextResponse.json(
        { error: 'Missing required parameter: param' },
        { status: 400 }
      );
    }

    // 4. Business logic
    const data = await db.query.someTable.findMany({
      where: eq(someTable.userId, auth.userId)
    });

    // 5. Success response
    return NextResponse.json({
      success: true,
      data,
      meta: {
        count: data.length,
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    // 6. Error handling
    logger.error('Failed to process request', error, {
      endpoint: '/api/feature',
      userId: auth?.userId
    }, LogCategory.API);

    return NextResponse.json(
      {
        error: 'Internal server error',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    // 1. Authentication
    const auth = await getAuthOrTest();
    if (!auth?.userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // 2. Parse body
    const body = await req.json();

    // 3. Validate input
    if (!body.name || !body.type) {
      return NextResponse.json(
        { error: 'Missing required fields: name, type' },
        { status: 400 }
      );
    }

    // 4. Business logic with logging
    logger.info('Creating resource', {
      userId: auth.userId,
      name: body.name
    }, LogCategory.API);

    const [resource] = await db.insert(someTable)
      .values({
        userId: auth.userId,
        name: body.name,
        type: body.type
      })
      .returning();

    // 5. Success response
    return NextResponse.json({
      success: true,
      data: resource
    }, { status: 201 });

  } catch (error) {
    logger.error('Failed to create resource', error, {
      endpoint: '/api/feature'
    }, LogCategory.API);

    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

Authentication Patterns

Primary Auth: /lib/auth/get-auth-or-test.ts

import { getAuthOrTest } from '@/lib/auth/get-auth-or-test';

// Standard pattern
const auth = await getAuthOrTest();
if (!auth?.userId) {
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

// With email access
const auth = await getAuthOrTest();
const email = auth?.sessionClaims?.email as string | undefined;

Auth Resolution Order:

  1. Test headers (x-test-user-id, x-test-email)
  2. Dev bypass header (x-dev-auth: dev-bypass)
  3. Environment bypass (ENABLE_AUTH_BYPASS=true)
  4. Clerk backendAuth()

Dev Bypass Methods:

  1. Header-Based:
curl http://localhost:3000/api/endpoint \
  -H "x-dev-auth: dev-bypass" \
  -H "x-dev-user-id: user_xxx"
  1. Environment-Based:
# .env.local
ENABLE_AUTH_BYPASS=true
AUTH_BYPASS_USER_ID=user_xxx
  1. Test Headers:
curl http://localhost:3000/api/endpoint \
  -H "x-test-user-id: user_xxx" \
  -H "x-test-email: [email protected]"

Response Formats

Success Response:

return NextResponse.json({
  success: true,
  data: result,
  meta: {
    count: result.length,
    page: 1,
    timestamp: new Date().toISOString()
  }
}, { status: 200 });

Error Response:

return NextResponse.json({
  error: 'Error message',
  code: 'ERROR_CODE', // Optional
  details: { /* ... */ } // Optional
}, { status: 400 });

Status Codes:

  • 200 - Success (GET, PUT, DELETE)
  • 201 - Created (POST)
  • 400 - Bad Request (validation failed)
  • 401 - Unauthorized (no auth)
  • 403 - Forbidden (auth but no permission, e.g., plan limits)
  • `404
Полный SKILL.md на GitHub

Установить api-route-conventions в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Write
Edit
Grep
Glob

Вложенные файлы

metadata.json

FAQ

Что делает скилл api-route-conventions?

Expert knowledge on Next.js API route patterns, authentication with getAuthOrTest, error handling, response formats, rate limiting, and webhook verification. Use this skill when user asks about "create api endpoint", "api route", "error handling", "authentication", "next.js api", or "route handler".

Как установить скилл api-route-conventions?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл api-route-conventions запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить api-route-conventions с