Redirect 404 Not Found in Nuxt.js

#Nuxt

This week I have two special announcements!

First, this Wednesday 10th, at 12.00PM CEST we’re opening the tickets of the VueDay in sunny Alicante, Spain. It’s going to be a community-driven Vue.js conference with great speakers including core members like the Chopin brothers, Eduardo San Martin, myself and more awesome ones!

Hope to see you there! Follow @VueDose on twitter to stay tuned with the latest news!

Second, I’m preparing the Vue Tips Overload! Over the next week, a tip will be published here by a different author each day. Are you as excited as I am?

That said, let’s jump into the tip!


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.

That’s it for this week! Remember you can read this tip online (with copy/pasteable code).

It’d be helpful if you also share VueDose with your colleagues, so they also know about these tips!

See you next week.

Do you want to sponsor a VueDose tip? Send an email to info@vuedose.tips and have more info!

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.