0
0
NextJSframework~5 mins

Error handling in server actions in NextJS

Choose your learning style9 modes available
Introduction

Error handling in server actions helps you catch problems and respond properly, so your app stays reliable and users get clear feedback.

When saving user data to a database and you want to handle failures gracefully.
When calling external APIs from a server action and need to manage errors like timeouts.
When validating input on the server and returning error messages for invalid data.
When performing file uploads or downloads and you want to catch issues like missing files.
When you want to log errors on the server for debugging and monitoring.
Syntax
NextJS
export async function actionName(formData) {
  try {
    // your server logic here
    return { success: true };
  } catch (error) {
    // handle error
    return { error: error.message };
  }
}

Use try...catch to catch errors inside server actions.

Return error info in a structured way so the client can show messages.

Examples
Catches database save errors and returns a simple error message.
NextJS
export async function saveUser(data) {
  try {
    await database.save(data);
    return { success: true };
  } catch (error) {
    return { error: 'Failed to save user.' };
  }
}
Handles network or API errors and returns the error message.
NextJS
export async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('API error');
    const data = await response.json();
    return { data };
  } catch (error) {
    return { error: error.message };
  }
}
Sample Program

This server action checks login data, throws errors for missing or wrong info, and returns success or error messages. It also sets a cookie on success.

NextJS
import { cookies } from 'next/headers';

export async function loginAction(formData) {
  try {
    const username = formData.get('username');
    const password = formData.get('password');

    if (!username || !password) {
      throw new Error('Username and password are required');
    }

    // Simulate user check
    if (username !== 'admin' || password !== '1234') {
      throw new Error('Invalid credentials');
    }

    // Set a cookie on successful login
    cookies().set('token', 'fake-jwt-token');

    return { success: true };
  } catch (error) {
    return { error: error.message };
  }
}
OutputSuccess
Important Notes

Always return errors in a consistent format so the client can handle them easily.

Do not expose sensitive error details to users; keep messages friendly and safe.

Use try...catch blocks inside server actions to catch both synchronous and asynchronous errors.

Summary

Error handling keeps your app stable and user-friendly.

Use try...catch inside server actions to catch and return errors.

Return clear error messages so the client can show helpful feedback.