Learn How to Handle 404 Not Found — Transcript

Transcript of the free Vue.js lesson Learn How to Handle 404 Not Foundwatch the video lesson.

At the moment, if we go to a route that doesn't exist, we just see a page with the navigation as there is no route that matches our params. Wouldn't it be better to have a not found page? Let's add a not found component with some text and a router link that goes to the homepage. In our router file, let's add another route.

The code for creating a catch all route looks like this. Here, we're using a custom param regular expression by adding the regex inside parentheses right after the param. If you're familiar with not found routes in Vue two, you'll remember that they can be defined with a star as the path. This no longer works in Vue three with Vue Router four.

The newer version looks a little more complex, but it actually gives us a lot more flexibility under the hood. And for a not found page, you'll only ever use it once in your application. And you can always just go to the router docs and copy and paste it, which is exactly what I did. Let's change the component to a dynamic import for performance's sake.

Now, if we go to our application and add any word in our route, we will see the not found component and clicking the link will take us home. We can also see in the view dev tools that we now have a route with the regex for the path and the name not found. And if we go to a route that doesn't exist, you will see it loads the not found component. However, if we go to the Brazil page and change the ID to thirty-three and the slug to Mexico, It doesn't give us the not found page.

What is going on here? In this case, the URL is matching the route pattern. So the router serves the route. So our problem is one level lower.

json file. And the router is not aware of what's in that file or what isn't. We need a way to check if the destination actually exists before we load the destination route. We can do this using a navigation guard.

We'll dive into that in the next lesson.