404 Error pages are very easy with Nuxt, but it took me long enough to find a how-to guide that I decided to write my own.
Custom 404 Error Page
The default Nuxt error page, that you probably have seen already, looks like this.
To write your custom error page simply create the file layouts/error.vue
. Here is an example:
<template>
<section>
<h1>404 Page not Found</h1>
</section>
</template>
Use the documentation of error pages and the source code of the default error page as reference.
404 Redirect
The above works nicely for routes that don't exist, but sometimes we want to redirect to the 404 page from another page programmatically.
In this example from my personal site Vue checks if the 404-error-page-and-redirect-with-nuxt.md
file exists to display the article. If no markdown file is found the user is redirected to the 404 page.
To achieve this I import the error
function in my asyncData
hook. If the server cannot find the file it forwards to the 404 page with error({ statusCode: 404 })
.
export default {
\\ ...
async asyncData ({ params, error }) {
try {
return await require(`~/writing/${params.slug}.md`)
} catch (e) {
error({ statusCode: 404, message: 'Article not found' })
}
},
\\ ...
}
Use the documentation for Handling Errors in asyncData
as reference.
Top comments (1)
Hi! Nice article! Error page is shown if doesn’t match any valid route, but the url stays the same wrong path. How can we handle it, if we want to change url to 404? Because custom error.vue is in layout, though we don’t have any access to asyncData context, we have fetch() but there is no $route or redirect there. Thank you!