Skip to main content

Part-1 VueJS JWT(JSON Web Token) Authentication(Access Token Implementation)

In this article, we are going to understand the steps for JWT(JSON Web Token) authentication. Here our main focus to fetch the JWT access token to make users log into our VueJS 3.0 application. For maintaining user info we will use Vuex state management.

JWT Token:

JSON Web Token is a digitally signed and secured token for user validation. The jwt is constructed with 3 informative parts:
  • Header
  • Payload
  • Signature

Create A VueJS 3.0 Sample Application:

Let's begin by creating a VueJS 3.0 sample application.
Command To Install Vue CLI Globally On Your System
npm install -g @vue/cli
Command To Create A Vue App:
vue create your_app_name

Required NPM Packages:

Need to install the Vue routing library to configure routing into our application.
Command To Install Vue Router Library(For Vue3.0)
npm install vue-router@4
Need to install the Vuex Store library to configure state management to our application
Command To Install Vuex Store Library(For Vue3.0)
npm install vuex@next
Install Axios library to invoke API call's in our application
Command To Install Axios Library
npm install axios

Basic Page Component And Route Configuration:

In this section, we will be going to implement vue js pages and their routes.

Let's use bootstrap design in our sample so add the below CSS reference link in the index.html page of our VueJS application
public/index.html:(Just above closing head tag)
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
Now add the Home component.
src/components/Home.vue:
<template>
    <div>
        <h4>Home Page</h4>
    </div>
</template>
<script>
export default {
    
}
</script>
Now add the Login Form component.
src/components/Login.vue:(Html Part)
<template>
  <div>
    <h4>Login Form</h4>
    <form>
      <div class="mb-3">
        <label for="txtuserName" class="form-label">User Name</label>
        <input
          type="text"
          class="form-control"
          id="txtuserName"
          aria-describedby="emailHelp"
          v-model="username"/>
      </div>
      <div class="mb-3">
        <label for="txtPassword" class="form-label">Password</label>
        <input
          type="password"
          class="form-control"
          id="txtPassword"
          v-model="password"
/> </div> <button type="button" class="btn btn-primary" @click="login()">Submit</button> </form> </div> </template>
  • Here we created a sample login form with model binding properties like 'username' and 'password'.
src/components/login.vue:(Script Part)
<script>
export default {
  data(){
   return{
	username:'',
	password:''
   }
  },
  methods:{
   login(){
	console.log(this.username, this.password);
   }
  }
};
</script>
  • Here we have model binding properties and the 'login' method.
Now update App.vue file with the navigation menu as below.
<template>
  <div>
   <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
	<div class="collapse navbar-collapse" id="navbarSupportedContent">
	  <ul class="navbar-nav me-auto mb-2 mb-lg-0">
		<li class="nav-item">
		  <router-link to="/" class="nav-link">Home</router-link>
		</li>
		 <li class="nav-item">
		  <router-link to="/login" class="nav-link">Login</router-link>
		</li>
	  </ul>
	</div>
    </div>
   </nav>
   <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
};
</script>
  • Here we added a bootstrap menu and also used the 'router-link' vue component for navigation and also used the 'router-view' vue component to render the content.
Now create a route configuration file.
src/appRouter.js:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import Login from './components/Login.vue';

const routes =[
  {path:'/', component:Home},
  {path:'/login', component:Login}
];

export const routeConfig = createRouter({
  history: createWebHistory(),
  routes: routes
});
Now register our route config file into our main.js file
src/main.js:
import { createApp } from 'vue'
import App from './App.vue'
import * as appRouter from './appRouter';

const app = createApp(App)
app.use(appRouter.routeConfig);
app.mount('#app')

A Basic Skeleton Structure Of Vuex State Management:

For accessing token or user data we will maintain it in Vuex State Management along with the browser local storage. So now here we will implement a basic structure of vuex state management in our sample application.
src/store/modules/auth.js:
const state = () => ({
  authData: {
    token: "",
    refreshToken: "",
    tokenExp: "",
    userId: "",
    userName: "",
  },
});

const getters = {};

const actions = {};

const mutations = {};

export default{
    namespaced:true,
    state,
    getters,
    actions,
    mutations
}
  • Here we are separating our states by using modules which means we can maintain the different states of an application as a module. Here we creating authentication as a separate state module into the auth.js file.
  • In general state mainly contains objects like 'state', 'getters', 'actions', and 'mutations'.
  • Inside of state object, we have created an object called 'authData' which maintains all information about the application authentication.
  • Defined to use namespace in the state to avoid the conflict between the method names
Now register our auth state module into the vuex store module.
src/store/index.js:
import { createStore } from "vuex";
import authModule from './modules/auth';

const store = createStore({
  modules:{
   auth:authModule
  }
});

export default store;
  • Here we registered our auth module, the property name we used to register our module is 'auth'. The 'auth' property name will be used as the namespace while using our store.
Now register vuex store into the vue instance of our application in the main.js file.
src/main.js:
import { createApp } from 'vue'
import App from './App.vue'
import * as appRouter from './appRouter';
import store from './store/index';

const app = createApp(App)
app.use(appRouter.routeConfig);
app.use(store);
app.mount('#app')

Mock JWT Access Token:

As a front-end developer no need to spend more time onto work on JWT authentication API (using nodejs, .net, java server programs). So let's use a sample JWT token by mocking it in a constant variable in our application, latter we will make a dynamic API call for fetching the Jwt token at the end section of this article.
A sample jwt token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJzdWIiOjEsImlhdCI6MTYwODIwNjE3OSwiZXhwIjozNjAxNjA4MjA2MTc5fQ.BcHKT6ffgvkt0EztkJT35a0Yc7iWF9wkeNxKB4wSJEQ

JWT Decoder:

As we know JWT token encrypted string which contains some information like 'username', 'expiration', and some other claims. So to decode the jwt access token use the below code snippet
src/shared/jwtHelper.js:
export function jwtDecrypt(token) {
  var base64Url = token.split(".")[1];
  var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
  var jsonPayload = decodeURIComponent(
    atob(base64)
      .split("")
      .map(function(c) {
        return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
      })
      .join("")
  );

  return JSON.parse(jsonPayload);
}

Implement Logic To Authenticate User Using Access Token:

Using mock jwt access token we will authenticate our user by storing the access token in browser local storage and in vuex state management as well.

Now update auth.js module state object with an additional property like 'loginStatus' this contains a message like authentication success or failure.
src/store/modules/auth.js:(Update 'state' object)
const state = () => ({
  authData: {
    token: "",
    refreshToken: "",
    tokenExp: "",
    userId: "",
    userName: "",
  },
  loginStatus:"",
});
Now update the mutations object to update our state in the auth.js module.
src/store/modules/auth.js:(Update 'mutations' object)
import { jwtDecrypt } from "../../shared/jwtHelper";

const mutations = {
  saveTokenData(state, data) {

    localStorage.setItem("access_token", data.access_token);
    localStorage.setItem("refresh_token", data.refresh_token);

    const jwtDecodedValue = jwtDecrypt(data.access_token);
    const newTokenData = {
      token: data.access_token,
      refreshToken: data.refresh_token,
      tokenExp: jwtDecodedValue.exp,
      userId: jwtDecodedValue.sub,
      userName: jwtDecodedValue.userName,
    };
    state.authData = newTokenData; 
  },
  setLoginStatu(state, value){
     state.loginStatus = value;
  }
};
  • Here in our mutation, we have defined 2 state change methods like 'SaveTokenData' and 'setLoginStatus'.
  • (Line: 2) The 'SaveTokenData' method accepts two parameters. The 'state' parameter nothing but our vuex state which will automatically be passed by the framework and the other is the 'data' parameter which is a user-defined input parameter where we passed our data into the method.
  • (Line: 4&5) Saving the token and refresh token data in local browser storage, so that they will be available to our application if we close and reopen our application as well.
  • (Line: 7) Decrypting the access token using our helper method defined above
  • Next updating the state of the 'authData' object.
  • (Line: 17-19) Setting the state of the 'loginStatus'.
Now we need to update the action method to get the access token from the API, for now, we will mock the access token in later steps we will update to use authentication API.
src/store/modules/auth.js:(Update 'actions' object)
const actions = {
  async login({commit},payload) {
    console.log(payload);
     const data = {
      access_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IlRlc3QiLCJzdWIiOjIsImlhdCI6MTYwNDMwOTc0OSwiZXhwIjoxNjA0MzA5ODA5fQ.jHez9kegJ7GT1AO5A2fQp6Dg9A6PBmeiDW1YPaCQoYs",
      refresh_token: ""
     }
     commit('saveTokenData', data);
     commit('setLoginStatu','success');
  },
};
  • (Line: 2) Defined action method 'login'. The reason we made this method async because in upcoming steps we will call authentication API which is an async call. This method has input parameter like '{commit}' this command to trigger the mutation which will be automatically passed by vuex and the second parameter is 'payload' user passing data(ex: user credential object).
  • (Line: 4) The constant object mocked with the access token.
  • (Line: 8)  Invoking the mutation method 'saveTokenData'
  • (Line: 9)  Invoking the mutation method 'setLoginStatus'
Now update the getter to fetch the status of 'loginStatus' property as below.
src/store/modules/auth.js:(Update getters object)
const getters = {
  getLoginStatus(state){
    return state.loginStatus;
  }
};
Now update the logic in Login.vue component to use the auth.js store to authenticate the user.
src/component/Login.vue:
<script>
import {mapActions, mapGetters} from 'vuex';
export default {
    data(){
        return{
            username:'',
            password:''
        }
    },
    computed:{
      ...mapGetters('auth',{
        getterLoginStatus:'getLoginStatus'
      })
    },
    methods:{
        ...mapActions('auth',{
          actionLogin:'login'
        }),
        async login(){
           await this.actionLogin({username:this.username, password:this.password});
           if(this.getterLoginStatus === 'success'){
             alert('login sucess');
           }else{
             alert('failed to login')
           }
        }
    }
};
</script>
  • (Line: 11-13) The 'getters' in the vuex state are used to fetch data. So to consume the getters in our vue component we need to use 'mapGetters' where we have to register our getters methods. The reason behind 'mapGetters' is used in 'computed' properties is that makes our data available with the latest updates.
  • (Line: 16-18) The 'actions' in the vuex state are to do async jobs like invoking API calls and then save the results to state by invoking mutations. So to trigger actions from the vue component we need to use 'mapActions' where we register vuex action methods.
  • (Line: 19-26) The 'login' method invoked when the user clicks on the login button. Here we first invoking 'actionLogin' which implicitly calls the 'login' action method states. After that checking the authentication state by using 'getterLoginStatus' which implicitly fetches data from the store.

Create A Dashboard Page:

Now let's create a sample user dashboard page where will display some user's data on it.

Now let's create a getter that fetches the 'authData' object in the auth.js module.
src/store/modules/auth.js:(Update getters object)
// code hidden for display purpose
const getters = {
  getAuthData(state){
    return state.authData;
  }
};
Create a new 'Dashboard' component where we display the user information.
src/components/Dashboard.vue:
<template>
    <div>
        <h1>Dashboard Page</h1>
        <div>
            UserName -- {{gettersAuthData.userName}}
        </div>
        <div>
            Id  -- {{gettersAuthData.userId}}
        </div>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
    computed:{
        ...mapGetters('auth',{
            gettersAuthData:'getAuthData'
        })
    }
}
</script>
  • Here fetching the user data using 'getAuthData' getter.
Update logic to navigate the user to the dashboard page in the Login component.
src/components/Login.vue:
async login(){
   await this.actionLogin({userName:this.username, password:this.password});
   if(this.getterLoginStatus === 'success'){
	 this.$router.push("/dashboard");
   }else{
	 alert('failed to login')
   }
}
Add the new route in the appRoutes.js file.
src/appRoute.js:
import Dashboard from './components/Dashboard.vue'

{path:'/dashboard',component: Dashboard}

Navigation Guards:

Navigation guards are used to executing navigation conditionally means if the non-authenticated user tries to access the page that requires authentication then the navigation guards will restrict the user from accessing the page.

In our sample example, the 'Dashboard' component needs user authentication, but if we try to access it without authentication also user able to see this component. So now we need to apply guards to protect our 'Dashboard' component.

In the jwtHelper.js file add a helper method to check the token expiration.
src/shared/jwtHelper.js:
export function tokenAlive(exp) {
  if (Date.now() >= exp * 1000) {
    return false;
  }
  return true;
}
  • The method returns 'true' if the token is still active.
Now create getter in our auth.js module to return a boolean value to identify user authenticated or not authenticated.
src/store/modules/auth.js:
import { tokenAlive } from "../../shared/jwtHelper";

const getters = {
  // code hidden for display purpose
  isTokenActive(state) {
    if (!state.authData.tokenExp) {
      return false;
    }
    return tokenAlive(state.authData.tokenExp);
  },
};
Now add the navigation guard in the appRouter.js file.
src/appRouter.js:
import { createRouter, createWebHistory } from "vue-router";
import Home from "./components/Home.vue";
import Login from "./components/Login.vue";
import Dashboard from "./components/Dashboard.vue";
import store from "./store/index";

const routes = [
  { path: "/", component: Home, meta: { requiredAuth: false } },
  { path: "/login", component: Login, meta: { requiredAuth: false } },
  { path: "/dashboard", component: Dashboard, meta: { requiredAuth: true } },
];

export const routeConfig = createRouter({
  history: createWebHistory(),
  routes: routes,
});

routeConfig.beforeEach((to,from, next) => {
    if(to.meta.requiredAuth){
        const auth = store.getters["auth/isTokenActive"];
        if(!auth){
           return next({path: '/login'});
        }
    }
    return next();
});
  • Here we can observe the routes new object like 'meta' is added. In this meta-object, we can define any properties. For our scenario, I have added property like 'requiredAuth' of type boolean, to differentiate which routes need authentication.
  • (Line: 18) Here we configured a global navigation guard that will execute for all routes before navigating. Inside of it, we added logic like based on 'requiredAuth' property we are checking user authentication and redirection.

Load Token On Application Open:

Now one problem we face is if we reload our application or closes & reopen the application we can observe we are in a logout state because all the data we maintained in the vuex store will be lost. So in this case we need to restore the store state by loading the access token from the browser's local storage.

So let's update our navigation guard to load the access token from the local browser storage.
src/appRoute.js:
routeConfig.beforeEach((to,from, next) => {
    console.log(store.getters["auth/getAuthData"].token);
    if(!store.getters["auth/getAuthData"].token){
        const access_token = localStorage.getItem("access_token");
        const refresh_token = localStorage.getItem("refresh_token");
        if(access_token){
            const data = {
                access_token:access_token,
                refresh_token:refresh_token
            };
            store.commit('auth/saveTokenData',data);
        }
    }
    const auth = store.getters["auth/isTokenActive"];

    if(to.fullPath == "/"){
        return next();
    }
    else if(auth && !to.meta.requiredAuth){
        return next({path:"/dashboard"});
    }
    else if(!auth && to.meta.requiredAuth){
        return next({path: '/login'});
    }

    return next();
});
  • (Line: 3-13) Loads the access token from the browser store and then updating the store state by populating the user data.

NestJS(Nodejs) Server JWT API:

Command To Install NestJS CLI:
npm i -g @nestjs/cli
Next, go to the root folder of the repo and run the command to install all the package
Command To Install ALL Packages In our Repository application:
npm install
That's all we have set up a JWT API in our local system for testing, now run the following command to start the application.
Command To Start NestJS APP:
npm run start:dev
Our jwt token endpoint
Url:- http://localhost:3000/auth/login
Payload:-
{
	"username":"test",
	"password":"1234"
}

note:- payload should be same as above, variable name 'username' and 'password'
don't change them, they are even case sensitive. credentials also use as above

Integrate JWT Authentication Endpoint:

Till now we used mocked jwt token, now we are going to use real Jwt authentication endpoint.

Let's update the 'login' action method in store
src/store/modules/auth.js:(Update login action method)
async login({ commit }, payload) {
    const response = await axios
      .post("http://localhost:3000/auth/login", payload)
      .catch((err) => {
        console.log(err);
      });
    if (response && response.data) {
      commit("saveTokenData", response.data);
      commit("setLoginStatu", "success");
    } else {
      commit("setLoginStatu", "failed");
    }
}
  • Here we replace our mock jwt token with real authentication API.
That's all about the steps to implement the access token in VueJS 3.0 application. In the next article, we will learn about the refresh token implementation.

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on access token implementation in VueJS 3.0 application. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

  1. Command To Install Vue CLI Globally On Your System

    npm install -g @vue/cli :)

    ReplyDelete
  2. Replies
    1. there might be issue with breaking changes, but logic you can implement as it is

      Delete
  3. Great article thank you very much!

    ReplyDelete
  4. Thank you very much, very useful !

    ReplyDelete
  5. Wondering if the access_token being sniffed in the transaction when calling API, will there be security breach that people can add the access_token to localstorage and impersonal another?

    ReplyDelete

Post a Comment

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually