Handle and redirect 404 responses in Nuxt.js

Alex Jover Morales

Alex Jover Morales

Apr 7, 2019
2 min read
Share on Twitter or LinkedIn

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.

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

Related Articles

Create Dynamic Titles and Favicons with Nuxt

Thinking on showing a timer on the browser tab? Or different favicons depending on a state? Learn to use vue-meta in your Vue.js apps in this tutorial

Javier Martínez

Javier Martínez

Jun 18, 2020

Auto Load Vuejs Components in Nuxt

Tired of writing imports all over your code? Read this tutorial to learn how to use Nuxt components module to automatically import your components

Debbie O'Brien

Debbie O'Brien

Jun 17, 2020

Simple transition effect between pages and layouts in Nuxt.js

In Nuxt.js, the Vue.js framework, it's very easy to apply transitions between pages and layouts on route changes. This tutorial explains how to.

Samuel Snopko

Samuel Snopko

Apr 17, 2019

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
StoryBlok
Learning Partner
Vue School