0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Lesson

Capturing Server Action Failures and Telemetry

Report action errors and performance metrics to an observability backend with user context.

Why Server Action Failures Need Special Treatment

Server Actions in Next.js 15 run on the server, outside the browser's error boundary. When a Server Action throws, the client receives a generic error — no stack trace, no context, no telemetry.

This means standard try/catch in the action is necessary but not sufficient. You also need to:

  • Capture the error with full server-side context (user ID, action name, request metadata)
  • Forward structured telemetry to an observability backend (e.g. OpenTelemetry, Sentry, Datadog)
  • Return a safe, serialisable error payload to the client — never expose raw stack traces

In this lesson you will build a complete, production-grade error-and-metrics pipeline around Server Actions.

Structuring a Safe Action Result Type

Before adding telemetry, agree on the shape every Server Action returns. A discriminated union makes error handling exhaustive on the client and prevents accidental data leaks.

Define this once in a shared types file and import it everywhere:

// lib/action-result.ts
export type ActionSuccess<T> = {
  ok: true;
  data: T;
  durationMs: number;
};

export type ActionFailure = {
  ok: false;
  code: string;       // machine-readable, e.g. 'VALIDATION_ERROR'
  message: string;    // human-readable, safe to show
  durationMs: number;
};

export type ActionResult<T> = ActionSuccess<T> | ActionFailure;

// Helper constructors
export function ok<T>(data: T, durationMs: number): ActionSuccess<T> {
  return { ok: true, data, durationMs };
}

export function fail(code: string, message: string, durationMs: number): ActionFailure {
  return { ok: false, code, message, durationMs };
}

All lessons in this course

  1. OpenTelemetry Tracing with instrumentation.ts
  2. Granular error.tsx and global-error Boundaries
  3. Structured Logging Across Server and Edge
  4. Capturing Server Action Failures and Telemetry
← Back to Next.js 15 Fullstack (App Router + Server Actions)