Javascript is required
·
1 min read

Nuxt Tip: Handle Client-Side Errors

Nuxt Tip: Handle Client-Side Errors Image

Nuxt will display a generic error page if an error occurs on the client-side. You often don't want to show a fullscreen error page but the error at a specific place in your app. Therefore, Nuxt provides the <NuxtErrorBoundary> component:

Component.vue
1<template>
2  <NuxtErrorBoundary>
3    <AnyComponent/>
4  </NuxtErrorBoundary>
5</template>

<NuxtErrorBoundary> will catch all errors in its default slot.

You can use the #error slot to display the error to the user. It provides an clearError function to clear the error and display the children again:

Component.vue
1<script setup lang="ts">
2const onError = (error: Error) => {
3  // Here you can try to resolve the error
4}
5</script>
6
7<template>
8  <NuxtErrorBoundary @error="onError">
9    <AnyComponent/>
10
11    <template #error="{ error, clearError }">
12      An error occurred: {{ error.message }}
13      <button @click="clearError">
14        Try again
15      </button>
16    </template>
17  </NuxtErrorBoundary>
18</template>

Warning

You can call error = null in onError to clear the error. However, this will re-render the default slot. If you haven't resolve the error completely yet, the error slot will be rendered again, which can lead to an infinite loop.

A solution is to navigate to a different page in onError:

Component.vue
1<script setup lang="ts">
2const recoverFromError = async (error) => {
3  await navigateTo('/');
4  error.value = null;
5}
6</script>

If you navigate to another route, the error will be cleared automatically.

Check out this live example that demonstrates how to handle errors in different contexts: pages, plugins, components and middleware.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.