Next.js course ยท Module 6: Forms and Server Actions

Error handling in Server Actions

7 min read ยท
In this lesson8

In Metropolis Quantum even the best systems can encounter errors - unexpected user input, database issues, or external API failures. Proper error handling in Server Actions is a key element of building reliable Next.js applications. In this lesson you'll learn patterns that will let you gracefully handle errors and inform users about them.

Try/catch in Server Actions

The basic error handling pattern in Server Actions is try/catch. Every server action should anticipate the possibility of an error occurring:

// app/actions.ts
'use server';

export async function createImplant(formData: FormData) {
  try {
    const name = formData.get('name') as string;
    const powerLevel = Number(formData.get('powerLevel'));

    // Operation that may fail
    const result = await db.implants.create({ name, powerLevel });

    return { success: true, data: result };
  } catch (error) {
    // NEVER return the raw error object to the client!
    console.error('Implant creation error:', error);
    return {
      success: false,
      error: 'Failed to create the implant. Please try again.'
    };
  }
}

Key rule: Server Actions should not throw exceptions to the client. Instead, return a structured object with success or error information.

Pattern for returning error objects

In professional applications, it's worth defining a consistent type for Server Actions responses:

// lib/types.ts
type ActionState = {
  status: 'idle' | 'success' | 'error';
  message: string;
  errors?: Record<string, string[]>; // Per-field form errors
};

// app/actions.ts
'use server';

export async function updateProfile(
  prevState: ActionState,
  formData: FormData
): Promise<ActionState> {
  const name = formData.get('name') as string;
  const email = formData.get('email') as string;

  // Validation
  const errors: Record<string, string[]> = {};

  if (!name || name.length < 2) {
    errors.name = ['First name must be at least 2 characters'];
  }
  if (!email || !email.includes('@')) {
    errors.email = ['Invalid email address format'];
  }

  if (Object.keys(errors).length > 0) {
    return {
      status: 'error',
      message: 'The form contains errors',
      errors,
    };
  }

  try {
    await db.users.update({ name, email });
    return { status: 'success', message: 'Profile updated!' };
  } catch (error) {
    return { status: 'error', message: 'Server error. Please try again.' };
  }
}

This pattern - an object with status, message, and an optional errors field - lets the client precisely understand what went wrong.

useActionState for displaying errors

The useActionState hook (formerly useFormState) is the official way to connect Server Actions with the user interface in React/Next.js:

'use client';

import { useActionState } from 'react';
import { updateProfile } from './actions';

const initialState = {
  status: 'idle',
  message: '',
  errors: {},
};

export default function ProfileForm() {
  const [state, formAction, isPending] = useActionState(
    updateProfile,
    initialState
  );

  return (
    <form action={formAction}>
      <div>
        <label htmlFor="name">First name</label>
        <input id="name" name="name" />
        {state.errors?.name && (
          <p className="text-red-500">{state.errors.name[0]}</p>
        )}
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input id="email" name="email" type="email" />
        {state.errors?.email && (
          <p className="text-red-500">{state.errors.email[0]}</p>
        )}
      </div>

      <button type="submit" disabled={isPending}>
        {isPending ? 'Saving...' : 'Save profile'}
      </button>

      {state.status === 'success' && (
        <p className="text-green-500">{state.message}</p>
      )}
      {state.status === 'error' && !state.errors && (
        <p className="text-red-500">{state.message}</p>
      )}
    </form>
  );
}

useActionState takes three arguments: the server action, the initial state, and returns an array: the current state, the formAction function (pass it to the form's action), and the isPending flag.

Zod validation in Server Actions

Combining Zod with Server Actions is a powerful pattern - the validation schema is shared between client and server:

// lib/schemas.ts
import { z } from 'zod';

export const implantSchema = z.object({
  name: z.string()
    .min(2, 'Implant name must be at least 2 characters')
    .max(50, 'Implant name can be up to 50 characters'),
  powerLevel: z.coerce.number()
    .min(1, 'Power level must be greater than 0')
    .max(100, 'Power level cannot exceed 100'),
  type: z.enum(['neural', 'cybernetic', 'bionic'], {
    errorMap: () => ({ message: 'Select an implant type' }),
  }),
});

// app/actions.ts
'use server';

import { implantSchema } from '@/lib/schemas';

export async function createImplant(prevState: any, formData: FormData) {
  // Validation with Zod
  const parsed = implantSchema.safeParse({
    name: formData.get('name'),
    powerLevel: formData.get('powerLevel'),
    type: formData.get('type'),
  });

  if (!parsed.success) {
    // Convert Zod errors to field -> messages format
    const fieldErrors: Record<string, string[]> = {};
    for (const issue of parsed.error.issues) {
      const field = issue.path[0] as string;
      if (!fieldErrors[field]) fieldErrors[field] = [];
      fieldErrors[field].push(issue.message);
    }
    return { status: 'error', message: 'Validation failed', errors: fieldErrors };
  }

  try {
    // parsed.data is typed and validated!
    await db.implants.create(parsed.data);
    return { status: 'success', message: 'Implant created!' };
  } catch (error) {
    return { status: 'error', message: 'Database write error' };
  }
}

Notice z.coerce.number() - converts a string from FormData to a number before validation. This is key because formData.get() always returns a string.

Custom error types

In complex applications, it's worth defining custom error types to distinguish their source:

// lib/errors.ts
export class ValidationError extends Error {
  constructor(
    public fieldErrors: Record<string, string[]>,
    message = 'Validation failed'
  ) {
    super(message);
    this.name = 'ValidationError';
  }
}

export class DatabaseError extends Error {
  constructor(message = 'Database error') {
    super(message);
    this.name = 'DatabaseError';
  }
}

export class AuthorizationError extends Error {
  constructor(message = 'Insufficient permissions') {
    super(message);
    this.name = 'AuthorizationError';
  }
}

// app/actions.ts
'use server';

import { ValidationError, DatabaseError, AuthorizationError } from '@/lib/errors';

export async function deleteImplant(prevState: any, formData: FormData) {
  try {
    const id = formData.get('id') as string;

    if (!id) {
      throw new ValidationError({ id: ['Implant ID is required'] });
    }

    const user = await getCurrentUser();
    if (!user?.isAdmin) {
      throw new AuthorizationError('Only administrators can delete implants');
    }

    await db.implants.delete(id);
    return { status: 'success', message: 'Implant deleted' };

  } catch (error) {
    if (error instanceof ValidationError) {
      return { status: 'error', message: error.message, errors: error.fieldErrors };
    }
    if (error instanceof AuthorizationError) {
      return { status: 'error', message: error.message };
    }
    if (error instanceof DatabaseError) {
      return { status: 'error', message: 'System error. Please try again later.' };
    }
    // Unknown error - don't expose details to the user
    console.error('Unexpected error:', error);
    return { status: 'error', message: 'An unexpected error occurred' };
  }
}

User-friendly messages

Error messages should be understandable and helpful - the user must know what to do:

// Bad messages:
"Error: ECONNREFUSED 127.0.0.1:5432"  // Technical, unintelligible
"Validation failed"                     // Too generic
"null"                                  // Nonsensical

// Good messages:
"Failed to save data. Check your connection and try again."
"Implant name must be at least 2 characters."
"Session expired. Log in again to continue."

Fallback behaviors

When a Server Action fails, the application should have a contingency plan:

'use client';

import { useActionState } from 'react';
import { saveData } from './actions';

export default function FormWithFallback() {
  const [state, formAction, isPending] = useActionState(saveData, {
    status: 'idle',
    message: '',
  });

  // Fallback: retry after error
  const handleRetry = () => {
    // Reset state and let the user try again
    window.location.reload();
  };

  if (state.status === 'error' && state.message.includes('server')) {
    return (
      <div>
        <p>A server problem occurred.</p>
        <button onClick={handleRetry}>Try again</button>
        <p>If the problem persists, contact the administrator.</p>
      </div>
    );
  }

  return (
    <form action={formAction}>
      {/* ... form fields ... */}
      <button type="submit" disabled={isPending}>
        {isPending ? 'Saving...' : 'Save'}
      </button>
    </form>
  );
}

Summary

Error handling in Server Actions is a critical element of reliable Next.js applications:

  • try/catch in every Server Action - never let raw errors reach the client
  • Structured error objects - { status, message, errors } instead of throwing exceptions
  • useActionState - official hook for connecting actions with UI and displaying per-field errors
  • Zod in Server Actions - safeParse() + z.coerce for validating data from FormData
  • Custom error types - distinguishing error sources (validation, authorization, database)
  • User-friendly messages - understandable, specific, with instructions on what to do next
Code for this lesson: App.tsx
import React, { useState } from 'react';

// Simulation of error handling in Server Actions (Next.js)
// try/catch, error objects, useActionState, Zod validation

type ActionState = {
  status: 'idle' | 'success' | 'error';
  message: string;
  errors?: Record<string, string[]>;
};

// Simplified validation (simulation of Zod safeParse)
function validateImplant(data: Record<string, string>) {
  const errors: Record<string, string[]> = {};
  if (!data.name || data.name.length < 2) {
    errors.name = ['Name must have at least 2 characters'];
  }
  if (!data.powerLevel || isNaN(Number(data.powerLevel))) {
    errors.powerLevel = ['A number is required'];
  } else {
    const pl = Number(data.powerLevel);
    if (pl < 1 || pl > 100) errors.powerLevel = ['Power level: 1-100'];
  }
  if (!data.type) {
    errors.type = ['Select an implant type'];
  }
  return { success: Object.keys(errors).length === 0, errors };
}

// Simulation of a Server Action with try/catch
async function createImplantAction(data: Record<string, string>): Promise<ActionState> {
  await new Promise(r => setTimeout(r, 800));

  // 1. Validation with Zod (safeParse)
  const validation = validateImplant(data);
  if (!validation.success) {
    return { status: 'error', message: 'Validation failed', errors: validation.errors };
  }

  // 2. Simulation of a server error
  try {
    if (data.name.toLowerCase() === 'error') {
      throw new Error('Database connection failed');
    }
    if (data.name.toLowerCase() === 'auth') {
      throw { type: 'AuthorizationError', message: 'No permission to create implants' };
    }
    return { status: 'success', message: `Implant "${data.name}" (power: ${data.powerLevel}) created!` };
  } catch (error: any) {
    // NEVER return the raw error to the client
    if (error.type === 'AuthorizationError') {
      return { status: 'error', message: error.message };
    }
    console.error('Server error:', error);
    return { status: 'error', message: 'Server error. Try again later.' };
  }
}

export default function ServerActionsErrorDemo() {
  const [values, setValues] = useState({ name: '', powerLevel: '', type: '' });
  const [state, setState] = useState<ActionState>({ status: 'idle', message: '' });
  const [isPending, setIsPending] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsPending(true);
    setState({ status: 'idle', message: '' });
    const result = await createImplantAction(values);
    setState(result);
    setIsPending(false);
  };

  const inputStyle: React.CSSProperties = {
    width: '100%', padding: '10px', background: '#0d1117',
    border: '1px solid #333', borderRadius: 6, color: '#e0e0e0',
    fontFamily: 'monospace', fontSize: 13, boxSizing: 'border-box'
  };

  const types = ['neural', 'cybernetic', 'bionic'];

  const codeExample = `// app/actions.ts
"use server";

export async function createImplant(prevState, formData) {
  const parsed = implantSchema.safeParse({...});
  if (!parsed.success) {
    return { status: 'error', errors: parsed.error.issues };
  }
  try {
    await db.implants.create(parsed.data);
    return { status: 'success', message: 'Created!' };
  } catch (error) {
    return { status: 'error', message: 'Server error' };
  }
}`;

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
      <h1 style={{ color: '#64ffda' }}>Handling Errors in Server Actions</h1>
      <p style={{ color: '#888', fontSize: 13, marginBottom: 12 }}>
        Type "error" in the name = server error. "auth" = no permissions. Empty fields = Zod validation.
      </p>

      <pre style={{ background: '#0d1117', border: '1px solid #333', borderRadius: 8, padding: 12, fontSize: 11, color: '#ce93d8', marginBottom: 16, whiteSpace: 'pre-wrap' }}>
{codeExample}
      </pre>

      <form onSubmit={handleSubmit} style={{ maxWidth: 400 }}>
        <div style={{ marginBottom: 12 }}>
          <label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Implant name</label>
          <input
            value={values.name}
            onChange={e => setValues(p => ({ ...p, name: e.target.value }))}
            placeholder="Neural Link"
            style={{ ...inputStyle, borderColor: state.errors?.name ? '#f44336' : '#333' }}
          />
          {state.errors?.name && <div style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{state.errors.name[0]}</div>}
        </div>

        <div style={{ marginBottom: 12 }}>
          <label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Power level (1-100)</label>
          <input
            value={values.powerLevel}
            onChange={e => setValues(p => ({ ...p, powerLevel: e.target.value }))}
            placeholder="75"
            style={{ ...inputStyle, borderColor: state.errors?.powerLevel ? '#f44336' : '#333' }}
          />
          {state.errors?.powerLevel && <div style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{state.errors.powerLevel[0]}</div>}
        </div>

        <div style={{ marginBottom: 12 }}>
          <label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Implant type</label>
          <div style={{ display: 'flex', gap: 8 }}>
            {types.map(t => (
              <button key={t} type="button" onClick={() => setValues(p => ({ ...p, type: t }))} style={{
                flex: 1, padding: '8px', borderRadius: 6, fontFamily: 'monospace', fontSize: 12, cursor: 'pointer',
                background: values.type === t ? '#1565c0' : '#0d1117',
                color: values.type === t ? '#fff' : '#aaa',
                border: `1px solid ${values.type === t ? '#64ffda' : state.errors?.type ? '#f44336' : '#333'}`
              }}>
                {t}
              </button>
            ))}
          </div>
          {state.errors?.type && <div style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{state.errors.type[0]}</div>}
        </div>

        <button type="submit" disabled={isPending} style={{
          background: isPending ? '#555' : '#e91e63', color: '#fff', border: 'none', borderRadius: 6,
          padding: '10px 20px', cursor: isPending ? 'wait' : 'pointer', fontFamily: 'monospace', width: '100%'
        }}>
          {isPending ? 'Validating on the server...' : 'createImplant() - Server Action'}
        </button>
      </form>

      {state.status !== 'idle' && !state.errors && (
        <div style={{
          marginTop: 16, borderRadius: 8, padding: 12, maxWidth: 400,
          background: state.status === 'success' ? '#1b5e20' : '#3e1010',
          border: `1px solid ${state.status === 'success' ? '#4caf50' : '#f44336'}`
        }}>
          <div style={{ color: state.status === 'success' ? '#4caf50' : '#f44336' }}>
            {state.message}
          </div>
        </div>
      )}
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Useful articles