Skip to content

Instantly share code, notes, and snippets.

@rudSarkar
Last active September 14, 2022 20:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rudSarkar/958e90ae8652b1a8a388f9e7fc60379a to your computer and use it in GitHub Desktop.
Save rudSarkar/958e90ae8652b1a8a388f9e7fc60379a to your computer and use it in GitHub Desktop.
Vue.js Vue Router dynamic route 404 handling to check exist post param or non-exist post param

Bellow code doesn't have any validation, when you send request http://example.com/post/this-is-my-first-blog it's exist but whenever you send http://example.com/post/wjhdsgdgdfgdfgfdgdfgd this request it also taken as valid request but don't sending to 404 page.

{
    path: '/post/:slug',
    name: 'PostDetails',
    component: postdetails
},
{
    path: '/404',
    name: 'Notfound',
    component: notfound
},
{
    path: '*',
    redirect: '/404'
}
  1. http://example.com/post/this-is-my-first-blog -> post exists
  2. http://example.com/post/wjhdsgdgdfgdfgfdgdfgd -> post donesn't exists

In this situation how you will validate your blog URL and non-exists URL

{
  path: '/post/:slug',
  name: 'PostDetails',
  component: postdetails,
  beforeEnter: (to, from, next) => {
   function isValid (param) {
      // check if param is valid
   }

    if (!isValid(to.params.slug)) {
      next({ name: 'Notfound' });
    }

    next();
  }
}

This is the solution to validate your url.Learn More Navigation Guards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment