Handle and redirect 404 responses in Nuxt.js
For me, Nuxt is one of the best pieces of software I've ever used. It makes me be so productive building web apps, no matter if they're SPA, Sever Side Rendered (SSR) apps, or static generated sites, following the JAM Stack trend.
Pss, in fact VueDose website is built on Nuxt as a static site 😉
But still, a lot of times find very interesting tricks that are not documented... that needs to stop! Let's share the first hot Nuxt tip!
If you're familiar with Nuxt.js, you should know the concept of pages. You should also know that there is a special Error page (well, it goes into the Layouts folder, but it's a page).
You can override the default error page and customize it to your needs... but what if we want a different behaviour?
In some cases, we might want that when a user visits a non existing page, we redirect him to the home page.
Here's the trick: you can do that easily by creating this pages/*.vue
component:
<!-- pages/*.vue -->
<script>
export default {
asyncData ({ redirect }) {
return redirect('/')
}
}
</script>
In Nuxt, routes are defined by the file naming convention. So when we create a *.vue
file, we're actually using a wildcard route on Vue Router.
Then, we use the redirect
method from the Nuxt context to perform the redirection, whether it's on the client or server.
We do that on the asyncData
method since we have the context there, but it would perfectly work with the fetch
method as well:
<!-- pages/*.vue -->
<script>
export default {
fetch({ redirect }) {
return redirect("/");
}
};
</script>
Go and try it out by typing any non-existent url. You should see how it is be redirected. It'd be helpful if you also share VueDose with your colleagues, so they also know about these tips!
See you next week.
Related Articles
How to use script setup in Nuxt 2
If you love Vue script setup and want to use it in your current Nuxt 2 project, the Nuxt team has made it possible to start using it today!
Feb 14, 2022
How to use the new Fetch in Nuxt.js
The Nuxt team is on fire, releasing new stuff every week! In this tip Samuel shows you a feature that might've gone unnoticed... till now.
Sep 7, 2020
Advanced i18n in Nuxt using Interpolations
Internationalization it's necessary in a multi-language site. Learn how to do i18n the right way in Nuxt and Vue using the nuxt-i18n module.
Aug 17, 2020
Sponsors
VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.