Create custom error page in Nuxt 3

Nuxt 3 is a powerful framework for building server-side rendered (SSR) Vue.js applications. One of the features it provides is the ability to create custom error pages, which can be a great way to improve the user experience of your application.

Here's how to create custom error pages in Nuxt 3:

  1. Create a new file in your root /directory called error.vue.
  2. Add the following code to the error.vue file:
<template>
    <h1>{{ error.statusCode }}</h1>
    <p>{{ error.message }}</p>
    <button @click="handleError()">Clear Errors</button>
</template>
<script setup>
const props = defineProps({
  error: Object
})

const handleError = () => clearError({ redirect: '/' })
</script>
Example code for error.vue

This code will display the status code and error message for any errors that occur in your application. When you click the button, you're redirected to your main page /. But what exactly do each of these functions do?

defineProps() is a function that returns the props (f.e. <Page foo="test" />) the component is given from its parent. Here it gets the error object, Nuxt passes it.

clearError() is the function used to get rid of the error and return to a "safe" site. Here we return on the click of a button to /.

Then, start your Nuxt 3 application with npm run dev and navigate to a non-existent page to see your custom error page in action!

That's it! With just a few lines of code, you can create custom error pages in Nuxt 3 that provides a better user experience for your application.

Show Comments