Home » vue » Validating JWT Token in vue.js Router

Validating JWT Token in vue.js Router

Posted by: admin November 26, 2021 Leave a comment


I am using the following code to generate a JWT token:

 jwt.sign(id, TOKEN_SECRET, { expiresIn: '24h' });

Once generated, I send the token to the client, which stores it within a cookie:

 document.cookie = `session=${token}` + ';' + expires + ';path=/'

Furthermore, I am using vue.js Router for my navigation. From my understanding, if one adds the following code in the router file, one can insert middle-ware in order to protect some routes.

 router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
   let token = Vue.cookie.get('session')
   if (token == null) {
      path: '/',
      params: { nextUrl: to.fullPath }
 } else {

However, I am having difficulty understanding how can one verify the validity of the JWT token using this approach, which needs to be done on the server, where the TOKEN_SECRET is stored, and not on the client side.


Let me start with this: your goal in guarding routes is to prevent the user from having a bad experience by proceeding to a page that will attempt to retrieve information that they are not authorized to view.

So, you don’t need to validate the token on the client side. Since a token will only be in hand if the server validated the user and returned a token, you – the author of the client code – can use the presence of the token as a means to inform what route to take the user through.

In other words, the client having a token is all the validation you need to allow the user through to protected routes.

Remember, it is not as though a protected page has private data in and of itself. A protected page will always retrieve that protected data from the server, which means that the server has the chance to authenticate the token after all.