Nuxt Tip: Handle Client-Side Errors
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:
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:
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 A solution is to navigate to a different page in If you navigate to another route, the error will be cleared automatically.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.onError
:1<script setup lang="ts">
2const recoverFromError = async (error) => {
3 await navigateTo('/');
4 error.value = null;
5}
6</script>
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:
Vue Tip: Best Way to Force Re-Render Vue Component
In certain scenarios, Vue's reactivity approach isn’t sufficient, and we need to force re-rendering of specific components.
Vue Tip: Watch Slot Changes
You can use the MutationObserver API to react to changes in the slot content.