Error Handling in Nuxt
Jakub Andrzejewski

Jakub Andrzejewski @jacobandrewsky

About: Senior Fullstack Developer & Advocate • @GoogleDevExpert in Web Performance • @nuxt_js Team • Ambassador @Storyblok, @algolia, @cloudinary, @supabase • Teaching Vue | Nuxt | Perf

Location:
Wrocław, Poland
Joined:
Jun 20, 2021

Error Handling in Nuxt

Publish Date: Jul 7
8 0

Nuxt 3, the latest evolution of the Nuxt framework, brings a powerful and flexible approach to building Vue applications using modern tooling like Vue 3, Vite, and Nitro. With these advancements comes a new error handling model that’s both robust and developer-friendly.

In this article, we’ll explore how error handling works in Nuxt 3, including built-in mechanisms, best practices, and how to implement custom error pages and logic.

Enjoy!

🤔 Why Error Handling Matters?

Effective error handling is critical in any application. It ensures that:

  • Users get a helpful message when something goes wrong.
  • Developers can diagnose and fix issues quickly.
  • Security is maintained by preventing sensitive error details from leaking.
  • The application maintains a good UX even under failure conditions.

🟢 Error Handling in Nuxt

Nuxt provides a built-in composable: useError() and utilities like createError() to manage errors gracefully.

The createError() function helps you throw custom errors that Nuxt understands and can catch.

export default defineEventHandler((event) => {
  const authorized = checkAuth(event);
  if (!authorized) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized',
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

Use the useError() composable to access error details within your pages:

<script setup>
const error = useError();

if (error) {
  console.log(error.statusCode); // For logging or conditionally displaying
}
</script>

<template>
  <div v-if="error">
    <h1>Error {{ error.statusCode }}</h1>
    <p>{{ error.message }}</p>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

You can create a custom error page by adding an error.vue file to the layouts directory:

<template>
  <div class="min-h-screen flex flex-col items-center justify-center">
    <h1 class="text-3xl font-bold text-red-600">Error {{ error.statusCode }}</h1>
    <p class="text-lg mt-4">{{ error.message }}</p>
    <NuxtLink to="/" class="mt-6 text-blue-500 underline">Go Home</NuxtLink>
  </div>
</template>

<script setup>
const error = useError();
</script>
Enter fullscreen mode Exit fullscreen mode

This layout will be automatically rendered for any uncaught error.

Middleware functions can also throw errors using createError. These will be caught and redirected to the error layout.

export default defineNuxtRouteMiddleware((to, from) => {
  const isAuthenticated = useAuthStore().loggedIn;
  if (!isAuthenticated && to.path !== '/login') {
    throw createError({
      statusCode: 403,
      statusMessage: 'Access Forbidden',
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

We can also configure a global error handler by using the Plugin like following:

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.config.errorHandler = (error, instance, info) => {
    // handle error, e.g. report to a service
  }

  // Also possible
  nuxtApp.hook('vue:error', (error, instance, info) => {
    // handle error, e.g. report to a service
  })
})

Enter fullscreen mode Exit fullscreen mode

Nuxt supports error boundaries using <NuxtErrorBoundary>—helpful for isolating and recovering from component-specific errors.

<template>
  <NuxtErrorBoundary>
    <MyComponent />
    <template #error="{ error }">
      <div class="text-red-500">Component error: {{ error.message }}</div>
    </template>
  </NuxtErrorBoundary>
</template>
Enter fullscreen mode Exit fullscreen mode

This is useful when you want localized error handling in specific parts of your UI.

📖 Learn more

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:

Vue School Link

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉

🧪 Advance skills

A certification boosts your skills, builds credibility, and opens doors to new opportunities. Whether you're advancing your career or switching paths, it's a smart step toward success.

Check out Certificates.dev by clicking this link or by clicking the image below:

Certificates.dev Link

Invest in yourself—get certified in Vue.js, JavaScript, Nuxt, Angular, React, and more!

✅ Summary

Nuxt makes error handling a first-class feature, giving developers intuitive tools to manage exceptions across both the client and server. With createError, useError, custom error layouts, and error boundaries, you can build resilient applications that handle failures gracefully.

Take care and see you next time!

And happy coding as always 🖥️

Comments 0 total

    Add comment