How to redirect a 404 route to Home using vue router in Vue.js 3

2.9k views Asked by At

Hello almighty community!

I have a little problem with Vue.js 3. In the router, I'm unable to define that any unknown route should be redirected to "/".

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
 {
    path: "/*",
    redirect: "/",
  }
]

Here, I have tested the redirect: "/" works, but path: "/*" is not working. Path "/" works only for domain.com/... I have also tested path: "*" but I get this error:

"Uncaught Error: Route "" should be "/"."

How do you do a 404 redirect in the latest Vue.js3?

1

There are 1 answers

1
Boussadjra Brahim On BEST ANSWER

In Vue router 4 which is compatible with Vue 3 you can Catch all / 404 Not found Route as follows:

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: "/",
  }
]

LIVE DEMO