·
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
<template> <NuxtErrorBoundary> <AnyComponent/> </NuxtErrorBoundary> </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
<script setup lang="ts"> const onError = (error: Error) => { // Here you can try to resolve the error } </script> <template> <NuxtErrorBoundary @error="onError"> <AnyComponent/> <template #error="{ error, clearError }"> An error occurred: {{ error.message }} <button @click="clearError"> Try again </button> </template> </NuxtErrorBoundary> </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
<script setup lang="ts"> const recoverFromError = async (error) => { await navigateTo('/'); error.value = null; } </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.