Skip to main content

Introduction

MicroCBM uses Next.js 15 Server Actions to handle all data operations with the backend API. These server-side functions are marked with "use server" and provide type-safe, authenticated communication with the REST API.

Architecture

All Server Actions are located in src/app/actions/ and follow a consistent pattern:
  • Authentication: Automatic token injection via requestWithAuth helper
  • Error Handling: Consistent error responses with status codes and messages
  • Type Safety: Full TypeScript types for requests and responses
  • Pagination: Standard pagination with page, limit, and metadata

Common Patterns

Authentication Flow

All actions automatically include the authentication token from cookies:
import { requestWithAuth } from "./helpers";

const response = await requestWithAuth("/api/v1/endpoint", {
  method: "GET",
});

Response Format

All mutation actions return an ApiResponse object:
interface ApiResponse {
  success?: boolean;
  statusCode?: number;
  message?: string;
  data?: Record<string, unknown>;
}

Pagination Format

List operations return paginated results:
interface GetResult<T> {
  data: T[];
  meta: {
    page: number;
    limit: number;
    total: number;
    total_pages: number;
    has_next: boolean;
    has_prev: boolean;
  };
}

Error Handling

Server Actions handle errors gracefully:
  • 403 Forbidden: Returns empty data array (permission denied)
  • Network Errors: Returns error with appropriate status code
  • Validation Errors: Returns error message from backend
const response = await addAssetService(payload);

if (response.success) {
  console.log("Asset created successfully");
  // response.data contains the created resource
}

Available Actions

Asset Management

CRUD operations for assets and sites, plus analytics. View Asset Actions →

Sample Management

Manage oil samples with wear metals, contaminants, and particle counts. View Sample Actions →

Sampling Points

Create and manage sampling points on assets for oil analysis collection. View Sampling Point Actions →

Sampling Routes

Organize sampling points into routes for systematic data collection. View Sampling Route Actions →

Alarm Management

Monitor and acknowledge alarms with linked recommendations. View Alarm Actions →

Recommendations

Create and manage maintenance recommendations with severity levels. View Recommendation Actions →

Organizations & Sites

Manage organizational hierarchy: organizations, sites, and departments. View Organization Actions →

User Management

Manage user accounts, activation, and profiles. View User Actions →

Role & Permission Management

Control role-based access with roles and permissions. View Role Actions →

Authentication

Handle user authentication, OTP verification, and password reset. View Auth Actions →

Usage in Components

Server Actions can be used in both Server Components and Client Components:
"use server";
import { getAssetsService } from "@/app/actions";

export default async function AssetsPage() {
  const { data: assets, meta } = await getAssetsService({
    page: 1,
    limit: 10,
  });

  return <AssetTable data={assets} meta={meta} />;
}

Best Practices

Always Check Response Status

Verify response.success before accessing data:
const response = await addAssetService(payload);

if (response.success) {
  // Safe to access response.data
} else {
  // Handle error with response.message
}

Handle Empty Results

List operations return empty arrays on permission errors:
const { data: assets } = await getAssetsService();

if (assets.length === 0) {
  return <EmptyState />;
}

Use Type Inference

Import payload types from @/schema for form validation:
import { AddAssetPayload, ADD_ASSET_SCHEMA } from "@/schema";
import { z } from "zod";

const form = useForm<AddAssetPayload>({
  resolver: zodResolver(ADD_ASSET_SCHEMA),
});

Next Steps

Asset Actions

Learn about asset and site management actions

Sample Actions

Explore oil sample analysis actions

Sampling Points

Manage sampling points on assets

Sampling Routes

Organize sampling collection routes

Alarm Actions

Discover alarm monitoring and acknowledgment

Recommendation Actions

View maintenance recommendation actions

User Management

Manage user accounts and profiles

Roles & Permissions

Control role-based access

Build docs developers (and LLMs) love