| | |

Nuxt 11 ๐Ÿ’š Error Handling & Resilience โ€” Handling server/client errors with createError, showError, error.vue, and NuxtErrorBoundary

โฑ๏ธ Estimated read: 13 min | |

Modern web applications must gracefully handle failures, ranging from missing API data to unexpected code crashes. Nuxt provides a unified error handling system that works across the server-side rendering phase and the client-side hydration phase. This system ensures that users are never met with a “white screen of death” and that search engines receive the correct HTTP status codes when content is missing or inaccessible.

This chapter explores the multi-layered approach to resilience in Nuxt. We will examine how to trigger errors intentionally using utility functions, how to catch and recover from component-level crashes using built-in components, and how to define a global fallback interface. By the end of this guide, you will understand how to build applications that stay functional even when parts of the system fail.

The sections below walk through the mechanics of error creation, the global error page structure, and the strategic use of error boundaries. We will also cover the critical differences between how errors are handled during a server-side request versus a client-side navigation.

Key point: Nuxt handles errors through a hierarchical strategy: NuxtErrorBoundary captures local component failures for graceful recovery, while error.vue acts as the final global fallback for unhandled exceptions and 404 responses.


Why Error Handling exists

The Hydration Mismatch problem. Because Nuxt runs code on both the server and the client, an error occurring during the transition (hydration) can break the interactivity of the entire page. Dedicated error handling ensures that if a client-side component fails to match the server-side output, the app can reset or display a fallback rather than freezing.

The SEO Status Code problem. Search engines rely on HTTP status codes like 404 (Not Found) or 500 (Internal Server Error) to index pages correctly. Without a structured error system, a missing page might still return a 200 OK status with a “Not Found” text message, which harms search ranking and crawl efficiency.

The “White Screen” problem. In standard Single Page Applications, a single JavaScript error in a deeply nested component can crash the entire rendering engine. Nuxt provides boundaries that “catch” these errors, allowing the rest of the application interface to remain functional while showing a specific error message in the affected area.

The API Unreliability problem. Modern apps depend on multiple microservices and external APIs. When a non-critical component fails to fetch data, the entire page shouldn’t fail. Nuxt allows developers to isolate these data-fetching errors so the user can still interact with other parts of the dashboard or site.

The User Experience problem. A raw JavaScript stack trace is confusing and intimidating to end-users. Nuxt’s error handling infrastructure allows developers to map technical failures to user-friendly messages and provide a clear “Try Again” or “Go Home” path, maintaining trust and usability.


a. Creating Errors with createError and showError

Nuxt provides two primary utilities for triggering errors manually: createError and showError. While they look similar, they serve different roles based on whether you want to return an error object or immediately interrupt the execution flow to show an error interface.

createError creates a personalized error object that includes extra metadata like statusCode and statusMessage. On the server, throwing an error created by createError will trigger a full-page error response.

// server/api/user.ts
export default defineEventHandler((event) => {
  const id = event.context.params?.id;
  if (!id) {
    // createError adds necessary metadata for Nuxt to recognize the error type
    throw createError({
      statusCode: 400,
      statusMessage: 'ID is required',
      fatal: true // Setting fatal to true forces a full-page error on the client
    });
  }
});

showError is a client-side utility used to trigger a full-screen error page immediately. This is useful when a navigation or a client-side interaction leads to an unrecoverable state where you want to redirect the user to the global error.vue.

<script setup lang="ts">
const handleClick = () => {
  // showError immediately triggers the global error page on the client side
  showError({ 
    statusCode: 404, 
    statusMessage: 'Page not found within the dashboard' 
  });
};
</script>

The fatal property is crucial. If an error is thrown on the client side during a navigation, Nuxt typically tries to handle it within the app. By setting fatal: true, you tell Nuxt that this error is unrecoverable and it should switch to the global error page immediately.


b. The Global error.vue

The error.vue file is a special component located in the root of your project (alongside app.vue). It is not a page and does not live in the pages/ directory. It is the final safety net for the entire application. When an unhandled error occurs, Nuxt unmounts the main application and mounts this component instead.

<!-- error.vue -->
<template>
  <div class="error-layout">
    <h1>Error {{ error.statusCode }}</h1>
    <p>{{ error.message }}</p>
    <!-- clearError is the helper to reset the app state and redirect -->
    <button @click="handleError">Clear error and go home</button>
  </div>
</template>

<script setup lang="ts">
// Nuxt automatically passes the 'error' object as a prop
const props = defineProps({
  error: Object
});

const handleError = () => {
  // clearError removes the error state and navigates the user
  clearError({ redirect: '/' });
};
</script>

This component must handle its own styling and layout, as it does not automatically use the files in the layouts/ directory. It receives an error prop containing the status code and message.

Crucially, you must use the clearError utility to exit the error state. Simply using useRouter().push('/') will not clear the internal Nuxt error state, and the error page may persist or reappear. clearError resets the application state and then performs the navigation.


c. Local Recovery with NuxtErrorBoundary

While error.vue handles global failures, NuxtErrorBoundary is used for localized failures. It allows you to wrap a specific component or section of your page. If an error occurs within that boundary, the boundary catches it, prevents it from bubbling up to the global level, and displays a fallback template instead.

<template>
  <div>
    <h2>User Dashboard</h2>
  
    <!-- The boundary catches errors in its default slot -->
    <NuxtErrorBoundary @error="logError">
      <template #default>
        <SidebarWidget /> <!-- If this crashes, the boundary takes over -->
      </template>

      <!-- The error slot provides the error object and a reset function -->
      <template #error="{ error, clearError }">
        <div class="alert">
          <p>The sidebar failed to load: {{ error.message }}</p>
          <button @click="recover(clearError)">Retry Loading</button>
        </div>
      </template>
    </NuxtErrorBoundary>

    <MainContent /> <!-- This part remains functional even if sidebar fails -->
  </div>
</template>

<script setup lang="ts">
const logError = (err: any) => {
  console.error('Captured local error:', err);
};

const recover = (clearError: () => void) => {
  // Perform logic to fix the state before clearing the error
  clearError();
};
</script>

This is the key to “Resilience.” Instead of the whole page breaking because a secondary widget failed, the widget shows an error message while the rest of the application remains interactive. This is particularly effective for dashboards, sidebars, or comment sections where data is fetched from multiple independent sources.

When using NuxtErrorBoundary, the @error event is emitted whenever an error is caught. The clearError function provided in the #error slot is used to reset the boundary and attempt to re-render the default slot.


Complete Example Session

// ============================================
// PART 1: THE GLOBAL ERROR PAGE (error.vue)
// ============================================
<template>
  <div class="fullscreen-error">
    <h2>Something went wrong</h2>
    <code>{{ error?.statusCode }} - {{ error?.statusMessage }}</code>
    <button @click="handleClear">Back to Safety</button>
  </div>
</template>

<script setup>
const props = defineProps(['error']); // Received from Nuxt
const handleClear = () => clearError({ redirect: '/' }); // Resets state
</script>

// ============================================
// PART 2: TRIGGERING A 404 SERVER-SIDE
// ============================================
// pages/products/[id].vue
<script setup>
const route = useRoute();
const { data: product } = await useFetch(`/api/products/${route.params.id}`);

if (!product.value) {
  // This causes the server to return a 404 status code to the browser
  throw createError({ statusCode: 404, statusMessage: 'Product Not Found', fatal: true });
}
</script>

// ============================================
// PART 3: LOCAL ERROR BOUNDARY IN LAYOUT
// ============================================
<template>
  <main>
    <nav>Navigation Bar</nav>
    <NuxtErrorBoundary>
      <slot /> <!-- Page content goes here -->
      <template #error="{ error, clearError }">
        <section class="crash-report">
          <p>This page crashed: {{ error.message }}</p>
          <button @click="clearError">Reset Page</button>
        </section>
      </template>
    </NuxtErrorBoundary>
  </main>
</template>

// ============================================
// PART 4: CLIENT-SIDE INTERACTION ERROR
// ============================================
<script setup>
const performAction = () => {
  try {
    throw new Error('Action failed'); // Logic error
  } catch (e) {
    // showError moves the user to error.vue on the client
    showError({ statusCode: 500, statusMessage: 'Process failed' });
  }
};
</script>

// ============================================
// PART 5: RECOVERING LOCAL STATE
// ============================================
<script setup>
const errorRef = ref(null);
const retryCount = ref(0);

const onLocalError = (err) => {
  errorRef.value = err;
  retryCount.value++;
};
</script>

// ============================================
// PART 6: PREVENTING BUBBLING
// ============================================
// If an error is caught by NuxtErrorBoundary, 
// it won't trigger error.vue unless you re-throw it.

// ============================================
// PART 7: API ERROR HANDLING (Nuxt 3 style)
// ============================================
// server/api/test.ts
export default defineEventHandler(() => {
  return createError({ statusCode: 401, message: 'Unauthorized access' });
});

// ============================================
// PART 8: CUSTOM ERROR OBJECTS
// ============================================
// Adding data to errors for use in the UI
const triggerComplexError = () => {
  throw createError({
    statusCode: 422,
    data: { field: 'email', reason: 'invalid' }
  });
};

// ============================================
// PART 9: THE USEERROR COMPOSABLE
// ============================================
// Accessing the current global error from any component
const globalError = useError();

// ============================================
// PART 10: CONTEXTUAL REDIRECTS
// ============================================
// Using clearError to send user to a specific dynamic path
const backToLogin = () => clearError({ redirect: '/auth/login' });

This session demonstrated the lifecycle of an error from being thrown on the server to being captured by a local boundary and finally being handled by the global error.vue fallback.


Quick Reference

Error Utilities

UtilityContextPrimary Purpose
createErrorServer/ClientCreates an error object with status codes
showErrorClientImmediately triggers the full-page error view
clearErrorClientResets the Nuxt error state and navigates
useErrorClientComposable to get the current global error

Error Properties (createError)

PropertyTypeDescription
statusCodeNumberHTTP status code (e.g., 404, 500)
statusMessageStringShort status text
messageStringHuman-readable error details
fatalBooleanIf true, forces global error page on client
dataObjectArbitrary payload for the error

NuxtErrorBoundary Slots

SlotPropDescription
default–The healthy components to be rendered
error{ error }The error object that was caught
error{ clearError }Function to attempt re-rendering the default slot

Best Practices

โœ… Do This:

// Always use clearError instead of router.push for error recovery
const reset = () => clearError({ redirect: '/' });            // โœ…

// Throw createError in setup for proper SSR status codes
if (!data) throw createError({ statusCode: 404, fatal: true }); // โœ…

// Wrap unstable third-party components in a boundary
<NuxtErrorBoundary> <ThirdPartyWidget /> </NuxtErrorBoundary> // โœ…

// Check useError() in app.vue for global logging
const error = useError(); if (error.value) log(error.value);   // โœ…

โŒ Don’t Do This:

// Don't use standard throw Error() for server status codes
throw new Error('Not Found'); // Returns 500, not 404          // โŒ

// Don't put error.vue inside the pages/ folder
// (It must be in the root directory)                          // โŒ

// Don't forget to use fatal: true for client-side redirection
throw createError({ statusCode: 404 }); // Stays on page       // โŒ

// Don't leave NuxtErrorBoundary without an #error slot
<NuxtErrorBoundary> <slot /> </NuxtErrorBoundary> // Empty UI  // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Error page won’t closerouter.push used instead of clearErrorUse clearError({ redirect: '/' })
404 shows 500 statuscreateError not used or missing statusCodeExplicitly set statusCode: 404 in createError
error.vue missing stylesIt doesn’t inherit from layouts/Define local styles or import a global CSS file
Boundary doesn’t catchThe error happened in an async callback/eventUse a try/catch and then showError or fatal error
Infinite retry loopsclearError called but same crash happensAdd a retry counter to prevent infinite loops

Real-World Examples

1. Basic 404 in Page Setup

if (!item) throw createError({ statusCode: 404, statusMessage: 'Item Missing', fatal: true });

2. Global Error Component

<template><div>{{ error.message }}<button @click="clearError()">Retry</button></div></template>

3. Client-Side API Failure

const fetchInfo = () => showError({ statusCode: 503, statusMessage: 'API Down' });

4. Component Error Boundary

<NuxtErrorBoundary @error="reportToSentry"><DefaultSlot /></NuxtErrorBoundary>

5. Recovery Function

const recover = (clear) => { state.value = null; clear(); };

6. Server-Side Permission Denied

throw createError({ statusCode: 403, statusMessage: 'Forbidden Area' });

7. Fetching Current Error State

const error = useError(); // Reactive error state for UI display

8. Conditional Layout on Error

<div v-if="error">Custom Error Layout</div><div v-else><slot /></div>

9. Validating Route Params

if (isNaN(route.params.id)) throw createError({ statusCode: 400 });

10. Fatal Error during Navigation

onBeforeRouteUpdate(() => { throw createError({ fatal: true }); });

Visual

The Error Flow Hierarchy

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  USER INTERACTION / SERVER REQUEST                      โ”‚
โ”‚                                                         โ”‚
โ”‚  1. Check: Is there a NuxtErrorBoundary?                โ”‚
โ”‚     YES โ”€โ”€โ–บ Capture Error โ”€โ”€โ–บ Show #error Template      โ”‚
โ”‚     NO  โ”€โ”€โ–บ Bubble Up                                   โ”‚
โ”‚                                                         โ”‚
โ”‚  2. Check: Is the error 'fatal' or Server-Side?         โ”‚
โ”‚     YES โ”€โ”€โ–บ Unmount App โ”€โ”€โ–บ Mount error.vue             โ”‚
โ”‚     NO  โ”€โ”€โ–บ Log to console / App stays running          โ”‚
โ”‚                                                         โ”‚
โ”‚  3. Exit State: clearError()                            โ”‚
โ”‚     Clears Internal State โ”€โ”€โ–บ Redirects User            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Server vs Client Logic

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚       SERVER-SIDE ERROR       โ”‚       โ”‚       CLIENT-SIDE ERROR       โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค       โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ 1. Code throws createError()  โ”‚       โ”‚ 1. Code throws createError()  โ”‚
โ”‚ 2. Nuxt stops rendering       โ”‚       โ”‚ 2. If fatal:true, mount error โ”‚
โ”‚ 3. Browser receives HTML/404  โ”‚       โ”‚ 3. If fatal:false, catch loc  โ”‚
โ”‚ 4. Search Engines see Status  โ”‚       โ”‚ 4. App remains interactive    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Recovery Loop

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  RECOVERY WORKFLOW                                      โ”‚
โ”‚                                                         โ”‚
โ”‚  [ CRASH ] โ”€โ”€โ–บ [ NuxtErrorBoundary ] โ”€โ”€โ–บ [ #error Slot ]โ”‚
โ”‚                                                โ”‚        โ”‚
โ”‚          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜        โ”‚
โ”‚          โ–ผ                                              โ”‚
โ”‚  [ Fix Application State ] โ”€โ”€โ–บ [ Call clearError() ]    โ”‚
โ”‚                                        โ”‚                โ”‚
โ”‚  [ Re-render Default Slot ] โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Global Fallbackerror.vue (Root Level)
Local Boundary<NuxtErrorBoundary>
Error CreatorcreateError({ ... })
Client TriggershowError({ ... })
Reset HelperclearError({ redirect: '/' })
Server BehaviorInterrupts SSR and sends status code
Client BehaviorBubble to boundary or switch to error page
ComposableuseError()

Key takeaways:

  • Nuxt matches server and client errors. Using createError on the server automatically translates to a 404 or 500 status code for the browser and SEO crawlers.
  • error.vue is the ultimate fallback. It sits at the root of the project and replaces the entire application when a fatal error occurs.
  • Always use clearError to recover. Standard navigation doesn’t reset Nuxt’s internal “error active” flag; only the helper function properly cleans up.
  • Boundaries prevent total failure. Wrap unstable parts of your UI in NuxtErrorBoundary to keep the rest of your application functional during partial outages.
  • The fatal flag is critical for client errors. Without fatal: true, a client-side error thrown in a setup script might not trigger the global error page.
  • SEO relies on status codes. Properly throwing errors in async Data or useFetch ensures search engines don’t index broken pages as “Healthy.”

Remember: Resilient Nuxt applications use a “Layered Defense” strategy. Use NuxtErrorBoundary for specific components that might fail due to data issues, and use error.vue as the global catch-all for routing and system failures. This combination ensures that the user is always presented with a clear path forward and that the application maintains a professional, reliable presence for both human users and automated search bots.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!