Redirect 404 in Vue Router - 51

Video thumbnail

Here I wanted to solve a small problem that occurs when we enter a route that doesn't exist. I already have the solution, so I'll comment on it for a moment. If we come to the application and try to enter any route that doesn't exist, for example, the root directly, we'll see a blank page. If we press F2 or look from here, I'll tell you that this route doesn't match any because we don't have it defined. That's the reason. The same thing happens if we go to another route that doesn't exist.

Solution 1: 404 via components

There are a couple of ways to fix this. One is to create a specific component. For demonstration purposes, I'm using the list category component:

src/router.js

const routes = [
   {
       path: '/dashboard',
       component: Base,
       children: [
           ***
   },
   {
       path: '/:pathMatch(.*)*', 
       name: 'NotFound', 
       component: YourComponent404
   },
]

Solution 2: 404 with Redirect

Suppose the component doesn't exist, or rather, suppose this component is intended to display a "404" message to let the client know the page doesn't exist. In this case, the component could be the solution. However, I don't think it's necessary to create a specific component for this purpose, especially in administrative applications. I don't see much point in displaying a 404 page. I think it's better to redirect the user to a valid page. To do this, we can place a redirect:

src/router.js

const routes = [
   {
       path: '/dashboard',
       component: Base,
       children: [
           ***
   },
   {
       path: '/:pathMatch(.*)*', 
       name: 'NotFound', 
       redirect: '/dashboard/movie'
   },
]

Redirection Explanation

Let me explain the redirection line a little bit. The important thing here is that when you enter a route that doesn't exist, for example, the root, instead of displaying a blank page or a 404 message, the application automatically redirects to a valid route. If, for example, we enter the root, as was exactly what I wanted to demonstrate, when this application is launched into production, we usually enter the domain, which in this case would be localhost:5173. But in production, let's suppose the domain is vuecodig.com. If you enter a route that doesn't exist, it would automatically redirect you to the destination page, instead of displaying a 404 page by default, as it did before.

I agree to receive announcements of interest about this Blog.

We will redirect to a component or route when the route does not exist.

- Andrés Cruz

En español