Server Actions

Server actions and mutations provide type-safe server-side functionality with client-side integration using React Query.

Project Structure

Directory Structure

server/
├── actions/           # Server actions
│   ├── auth-actions.ts
│   ├── user-actions.ts
│   └── workspace-actions.ts
└── db/
    └── mutations/     # Client-side mutations
        ├── use-user-api.ts
        ├── use-workspace-api.ts
        └── use-member-api.ts

Server Actions

server-only

Server-Side Implementation

Server actions are located in server/actions/ and handle server-side operations with built-in error handling and rate limiting.

Example: User Action

Server-side implementation of user creation:

TYPESCRIPT

Client Mutations

use-hooks

Client-Side Integration

Client mutations are React hooks located in server/db/mutations/ that wrap server actions with React Query for state management.

Example: User Mutation Hook

Client-side mutation hook for user creation:

TYPESCRIPT

Usage in Components

Component Implementation

Example: Using Mutations

Using mutation hooks in React components:

TYPESCRIPT

Key Features

⏱️

Rate Limiting

Built-in rate limiting using Upstash Redis

🛡️

Error Handling

Standardized error handling with custom error types

🔒

Type Safety

Full TypeScript support with Zod validation

🔄

State Management

Automatic cache invalidation with React Query

Best Practices

Server Actions

  • 1
    Use 'use server' directive
  • 2
    Implement proper validation
  • 3
    Handle all error cases
  • 4
    Use transactions for related operations

Client Mutations

  • 1
    Prefix mutation functions with 'server_'
  • 2
    Handle loading states
  • 3
    Provide meaningful error messages
  • 4
    Update UI optimistically when possible

All server actions should be properly rate-limited and validated to prevent abuse. Always handle errors appropriately and provide meaningful feedback to users. Learn more about rate limiting and error handling