Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

The error page and createError

When a page is not found or the server fails, Nuxt shows an error page. By default it is Nuxt's standard placeholder; your own error page goes into the file app/error.vue. You can raise such an error from code with the createError function.

Your own error page

Create the file app/error.vue (not in the pages folder, but directly in app/):

<!-- app/error.vue -->
<script setup lang="ts">
import type { NuxtError } from '#app'
 
defineProps<{ error: NuxtError }>()
</script>
 
<template>
  <main>
    <h1>Error {{ error.statusCode }}</h1>
    <p>{{ error.message }}</p>
  </main>
</template>

Nuxt passes the error in the error prop: statusCode holds the code and message the text. Open an address that does not exist, such as /contacts, and you see "Error 404" with a text saying the page was not found.

Getting back to the site

The error page replaces the whole app, even the layout. To leave it, call clearError:

<!-- app/error.vue -->
<script setup lang="ts">
import type { NuxtError } from '#app'
 
defineProps<{ error: NuxtError }>()
 
function goHome() {
  clearError({ redirect: '/' })
}
</script>
 
<template>
  <main>
    <h1>Error {{ error.statusCode }}</h1>
    <p>{{ error.message }}</p>
    <button @click="goHome">Go home</button>
  </main>
</template>

The button clears the error and opens the home page.

A 404 error for a post

If a post does not exist, the API returns 404, but the page /posts/99 shows an empty space. Turn it into a real error:

<!-- app/pages/posts/[id].vue -->
<script setup lang="ts">
const route = useRoute()
const { data: post } = await useFetch(() => `/api/posts/${route.params.id}`)
 
if (!post.value) {
  throw createError({
    statusCode: 404,
    message: 'Post not found',
    fatal: true
  })
}
</script>

Now /posts/99 shows the error page with "Post not found", and search engines receive the 404 status code. The fatal: true option makes the error page appear also when navigating by a link in the browser, not only on the first load from the server.

Ways to raise an error

FunctionWhere to use it
throw createError(...)In <script setup>, middleware and server handlers
showError(...)In event handlers in the browser
clearError({ redirect: '/' })On the error page, to go back

If an error should affect only part of a page, wrap that part in the <NuxtErrorBoundary> component: on an error inside it, fallback content is shown and the rest of the page keeps working.

Common mistake

Putting a plain <NuxtLink to="/"> on the error page. The error state is not cleared this way, and the user may stay on the same error page. To leave, use clearError({ redirect: '/' }): it both clears the error and navigates.

Thanks for reading!

Donate to the site — we work hard for you.