Skip to content

add-api-endpoint

Access: /template add-api-endpoint or /t add-api-endpoint

Creates API endpoints in a MakerKit project using either Server Actions for mutations or Route Handlers for REST APIs, following MakerKit's established patterns.

What It Does

The add-api-endpoint command helps you create properly structured API endpoints with:

  • Authentication and authorization
  • Input validation using Zod schemas
  • Error handling with user-friendly messages
  • Proper TypeScript types
  • Database integration with RLS policies
  • Revalidation for cache management

Usage

bash
/template add-api-endpoint "Description"
# or
/t add-api-endpoint "Description"

When prompted, specify:

  • Endpoint type (Server Action or Route Handler)
  • Resource name
  • Operations needed (CREATE, READ, UPDATE, DELETE)
  • Authentication requirements

Prerequisites

  • A MakerKit project initialized with Orchestre
  • Database tables created for the resource
  • Commercial MakerKit license from MakerKit

Implementation Patterns

Server Actions (Preferred for Mutations)

Server Actions are the recommended approach for data mutations in MakerKit. They provide:

  • Built-in CSRF protection
  • Automatic type safety
  • Simplified error handling
  • Direct integration with forms

Example structure:

apps/web/app/home/[account]/
├── _lib/
│   ├── schema/
│   │   └── resource.schema.ts
│   └── server/
│       └── server-actions.ts
└── _components/
    └── resource-form.tsx

Route Handlers (For REST APIs)

Use Route Handlers when you need:

  • RESTful API endpoints
  • External webhook endpoints
  • File upload handling
  • Third-party integrations

Example structure:

apps/web/app/api/v1/
└── resources/
    ├── route.ts              # Collection endpoints
    └── [resourceId]/
        └── route.ts          # Item endpoints

What Gets Created

For Server Actions

  1. Zod Schemas (_lib/schema/)

    • Input validation schemas
    • Type-safe data contracts
  2. Server Actions (_lib/server/server-actions.ts)

    • CRUD operations wrapped with enhanceAction
    • Automatic authentication checks
    • Cache revalidation
  3. Client Integration

    • Form components with useTransition
    • Error handling with toast notifications
    • Loading states

For Route Handlers

  1. Route Files (app/api/v1/)

    • HTTP method handlers (GET, POST, PUT, DELETE)
    • Request/response handling
    • Proper status codes
  2. Authentication

    • Uses requireUser for auth checks
    • Scoped data access
  3. Error Responses

    • Consistent error format
    • Validation error details

Example

Creating a "Tasks" API:

bash
/template add-api-endpoint "Description"
# or
/t add-api-endpoint "Description"

Input:

  • Type: "Server Action"
  • Resource: "tasks"
  • Operations: "CREATE, UPDATE, DELETE"

This creates:

typescript
// Server action with authentication and validation
export const createTaskAction = enhanceAction(
  async (data, user) => {
    // Implementation
  },
  {
    auth: true,
    schema: CreateTaskSchema,
  }
);

Key MakerKit Utilities

The command uses these MakerKit utilities:

  • enhanceAction: Wraps server actions with auth and validation
  • requireUser: Ensures authentication in route handlers
  • getSupabaseServerClient: Server-side database client
  • getSupabaseRouteHandlerClient: Route handler database client

Best Practices

Choose the Right Pattern

  • Server Actions: For form submissions and data mutations
  • Route Handlers: For REST APIs and external integrations

Error Handling

  • Throw errors with user-friendly messages in Server Actions
  • Return proper HTTP status codes in Route Handlers
  • Always validate input with Zod schemas

Performance

  • Use revalidatePath for granular cache updates
  • Implement pagination for list endpoints
  • Add appropriate database indexes

Post-Creation Steps

  1. Update TypeScript types:

    bash
    pnpm db:typegen
  2. Test the endpoint:

    bash
    pnpm dev
    # Test with your API client
  3. Add tests:

    • Unit tests for business logic
    • Integration tests for API endpoints

Common Patterns

Pagination (Route Handlers)

typescript
const limit = parseInt(searchParams.get('limit') || '10');
const offset = parseInt(searchParams.get('offset') || '0');

Optimistic Updates (Server Actions)

typescript
const [pending, startTransition] = useTransition();
startTransition(async () => {
  // Optimistic UI update
  await serverAction(data);
});

Batch Operations

typescript
export const batchUpdateAction = enhanceAction(
  async ({ ids, updates }, user) => {
    // Batch update logic
  },
  { auth: true, schema: BatchUpdateSchema }
);

License Requirement

Important: This command requires a commercial MakerKit license from https://makerkit.dev?atp=MqaGgc MakerKit is a premium SaaS starter kit and requires proper licensing for commercial use.

Built with ❤️ for the AI Coding community, by Praney Behl