Skip to main content

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 notification to enable routing like '(y/n)' please enter 'y'(yes) For our demo we use routing as well.

Let's explore a few default files in the angular project:
  • package.json - contains commands like build, run, test, etc. It also contains packages or library references that our angular application requires.
  • angular.json - contains setup and configurations of angular.
  • src/index.html - Only HTML file of the angular application. It contains the root angular component element like <app-root></app-root>, area for our components to rendered.
  • src/main.ts - entry file of our angular application to execute.
  • src/app/app.modulet.ts - Entry module.
  • src/app/app-routing.module.ts - Entry route module
  • app(folder or root component folder) - contains root component like 'AppComponent' consist of files like 'app.component.ts', 'app.component.html', 'app.component.css'.

Setup JSON Server:

Let's set up a fake API by setting up the JSON server in our local machine.

Run the below command to install the JSON server global onto your local system.
npm install -g json-server

Now go to our angular application and add a command to run the JSON server into the 'package.json' file
"json-run":"json-server --watch db.json"

Now to invoke the above-added command, run the below command in the angular application root folder.
npm run json-run

After running the above command for the first time, a 'db.json' file gets created, so this file act as a database. So let's add some sample data into the file as below.
Now access API endpoint like 'http://localhost:3000/fruits'.

Install And Configure Bootstrap:

Let's install the bootstrap package into our angular application
npm install bootstrap

Add the bootstrap 'JS' & 'CSS' file path in 'angular.json'.

Add the bootstrap menu to the 'app.component.html' file
src/app/app.component.html:
<nav class="navbar navbar-expand-lg navbar-dark bg-warning">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Fruit Bowl</a>
  </div>
</nav>
<router-outlet></router-outlet>
  • (Line: 1-5) Render the bootstrap menu
  • (Line: 6) The 'router-outlet' is the default angular component. The content of every route is rendered into it.

Create A Example Module(Ex: Fruits Module):

Let's create a sample 'Fruits' module along with its route module. Run the below command.
ng generate module fruits --routing


Now add our 'FruitModule' into the imports of the 'AppModule'.

Create A Home Component:

Let's create a child component like 'Home' inside of the 'fruits' module. The 'Home' component will display all the items.
ng generate component fruits/home


Add HomeComponent rout in the 'FruitsRoutingModule'.
src/app/fruits/fruits-routing.module.ts:
// existing code hidden for display purpose

import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: 'fruits/home',
    component: HomeComponent,
  },
];
Now make the 'fruits/home' route as the default route by adding a redirection in the 'AppRoutingModule'.
src/app/app-routing.modulet.ts:
// code hidden for display purpose

const routes: Routes = [
  {
    path: '',
    redirectTo: 'fruits/home',
    pathMatch: 'full',
  },
  
];

Create A Service File:

Create an angular service file where we are going to implement the logic for API calls.
ng generate service fruits/fruits

Now inject the 'HttpClient' instance into the service constructor. The 'HttpClient' provides in-built methods for invoking the API's
src/app/fruits/fruits.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class FruitsService {
  constructor(private http: HttpClient) {}
}
In 'AppModule' add 'HttpClientModule' to the imports array.
src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http';
// code hidden for display purpose

@NgModule({
  imports: [
    HttpClientModule
  ],
})
export class AppModule { }

Create API Response Model:

Let's create a model for the API response.
ng generate interface fruits/fruits
src/app/fruits/fruits.ts:
export interface Fruits {
  id: number;
  name: string;
  quantity: number;
  price: number;
}

Read Operation:

The Read operation means reading the data from the API.

In 'FruitService' let's implement logic to invoke the API call.
src/app/fruits/fruits.servicet.ts:
get() {
  return this.http.get<Fruits[]>('http://localhost:3000/fruits');
}
  • The 'HttpClient.get<T>()' is to invoke the HTTP Get endpoint.
Add the following logic into the 'HomeComponent'.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  allFruits: Fruits[] = [];

  constructor(private fruitService: FruitsService) {}

  ngOnInit(): void {
    this.get();
  }

  get() {
    this.fruitService.get().subscribe((data) => {
      this.allFruits = data;
    });
  }
}
  • (Line: 5-9) To make 'HomeComponent' as angular component it should be decorated with '@Component' decorator that loads from the '@angular/core'. The 'selector' property for define the component Html element tag. The 'templateUrl' property for to link the component Html file. The 'styleUrls' property for to link the component CSS file.
  • (Line: 11) Variable 'allFruits' is of  'Fruits' array type. This variable is to store all API response data into this variable.
  • (Line: 19-23) Here defined method like 'get()'. Invoking the get API call in service file. Here 'subscribe()' get executed after completion of the API call. On receiving response assign to the 'allFruits' variable.
  • (Line: 15-17) The 'ngOnInit()' is one of the angular component life cycle method. This method executed automatically on invoking our 'HomeComponent'. Inside of this method we invoke our 'get()' method.
Add the following HTML into the 'HomeComponent.html' file.
src/fruits/home/home.component.html:
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Id</th>
        <th scope="col">Name</th>
        <th scope="col">Quantity</th>
        <th scope="col">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of allFruits">
        <th scope="row">{{ item.id }}</th>
        <td>{{ item.name }}</td>
        <td>{{ item.quantity }}</td>
        <td>{{ item.price }}</td>
      </tr>
    </tbody>
  </table>
</div>
  • Angular for databinding bind the we use '{{}}'(string interpolation) 
  • (Line: 12) The 'allFruits' is array, to loop it over the HTML content we have to use '*ngFor'. In *ngFor we will use array of object like 'allFruits', the 'of' keyword to popsout each item from  the array and assign to the variable 'item'
  • (Line: 13-16) Rendering the data to the bootstrap table.
Now run both angular(ng serve) and API (npm run json-run).

Generate A 'Create' Component:

Generate a new child component like 'Create' under the 'fruits' module. This component contains a form for creating the new items.
ng generate component fruits/create


Add route for 'Create' component into 'FruitRouteModule'.
src/app/fruits/fruits-routing.module.ts:
// existing code hidden for display puporse
import { CreateComponent } from './create/create.component';

const routes: Routes = [
  {
    path: 'fruits/home',
    component: HomeComponent,
  }
];

Create Operation:

Let's implement the logic for invoking the save API call in  'FruitsService'.
src/app/fruits/fruits.service.ts:
create(payload: Fruits) {
  return this.http.post<Fruits>('http://localhost:3000/fruits', payload);
}
  • The 'HttpClient.post<T>(payload)' method is invoke the HTTP Post endpoint for saving at the server.
Let's update the logic in the 'CreateComponent.ts' file.
src/app/fruits/create/create.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
})
export class CreateComponent implements OnInit {
  fruitForm: Fruits = {
    id: 0,
    name: '',
    price: 0,
    quantity: 0,
  };

  constructor(private fruitService:FruitsService,
    private router:Router) {}

  ngOnInit(): void {}

  create(){
    this.fruitService.create(this.fruitForm)
    .subscribe({
      next:(data) => {
        this.router.navigate(["/fruits/home"])
      },
      error:(err) => {
        console.log(err);
      }
    })
  }
}
  • (Line: 12-17) Declared the 'fruitForm' variable to store the user entered form data.
  • (Line: 19-20) Injected the 'FruitsService' and 'Router'.
  • (Line: 24-34) Invoking the API call to post the data.
  • (Line: 28) On successful saving data to the server, we navigate to the home page.
Add the following HTML code to the 'CreateComponent.html' file.
src/app/fruits/create/create.component.hmtl:
<div class="container">
  <legend>Create Item</legend>
  <form>
    <div class="mb-3">
      <label for="txtName" class="form-label">Name</label>
      <input type="text" name="name" [(ngModel)] = "fruitForm.name" class="form-control" id="txtName" />
    </div>
    <div class="mb-3">
      <label for="txtPrice" class="form-label">Price</label>
      <input type="number" name="price" [(ngModel)] = "fruitForm.price" class="form-control" id="txtPrice" />
    </div>
    <div class="mb-3">
      <label for="txtQuantity" class="form-label">Quantity</label>
      <input type="number" name="quantity" [(ngModel)] = "fruitForm.quantity" class="form-control" id="txtQuantity" />
    </div>
    <button type="button" (click)="create()" class="btn btn-primary">Create</button>
  </form>
</div>
  • Here enable 2-way model binding using '[(ngModel)]'. One more important thing here is that the input element must contain the 'name' attribute for 2-way model binding.
  • Click event can be a register like '(name_of_event)' and the event must register with the method so that on raise of event logic inside of the method gets executed.
Add the 'FormModule'(required for ngModel) into the import array of 'FruitsModule'.
src/app/fruits/fruits.module.ts:
// existing code hidden for display purpose
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule
  ]
})
export class FruitsModule { }
In 'HomeComponent.html' add a button for navigating the 'CreateComponent'.
src/app/fruits/home/home.component.html:
<div class="container">
  <div class="row mt-2">
    <div class="col col-md-4 offset-md-4">
      <a class="btn btn-primary" routerLink="/fruits/create">Create</a>
    </div>
  </div>
  <table class="table">
	<!-- code hidden for display purpose -->
  </table>
</div>
  • Here 'routerLink' is an angular directive used for anchor tags for navigation.
(Step 1)

(Step 2)

(Step 3)

Generate A 'Edit' Component:

Generate new child components like 'Edit' under the 'Fruits' module. This component contains the form for updating the items 
ng generate component fruits/edit

Add route for 'Edit' component into 'FruitModule'.
src/app/fruits/fruits-routing.module.ts:
import { EditComponent } from './edit/edit.component';

// existing code hidden for display purpose

const routes: Routes = [
  {
    path:'fruits/edit/:id',
    component: EditComponent
  }
];

Update Operation:

In our 'FruitService' implement the logic for 2 API calls, one for fetching items by id and another for updating the data.
src/app/fruits/fruits.service.ts:
getById(id: number) {
 return this.http.get<Fruits>(`http://localhost:3000/fruits/${id}`);
}

update(payload:Fruits){
 return this.http.put(`http://localhost:3000/fruits/${payload.id}`,payload);
}
  • (Line: 1-3) Invokes the HTTP Get endpoint by 'id' value as a filtering parameter.
  • (Line: 5-7) Invokes the HTTP Put endpoint for updating the item. Here 'id' value needs to be passed in the URL and edited data as a payload.
Now add the following logic into the 'edit.component.ts' file
src/app/fruits/edit/edit.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css'],
})
export class EditComponent implements OnInit {
  fruitForm: Fruits = {
    id: 0,
    name: '',
    price: 0,
    quantity: 0,
  };
  constructor(
    private route: ActivatedRoute,
    private router:Router,
    private fruitService: FruitsService
  ) {}

  ngOnInit(): void {
    this.route.paramMap.subscribe((param) => {
      var id = Number(param.get('id'));
      this.getById(id);
    });
  }

  getById(id: number) {
    this.fruitService.getById(id).subscribe((data) => {
      this.fruitForm = data;
    });
  }

  update() {
    this.fruitService.update(this.fruitForm)
    .subscribe({
      next:(data) => {
        this.router.navigate(["/fruits/home"]);
      },
      error:(err) => {
        console.log(err);
      }
    })
  }
}
  • (Line: 12-17) Declared the 'formFruits' variable to store the user form edited data.
  • (Line: 18-22) Injected the 'ActivatedRoute', 'Router', 'FruitService'.
  • (Line: 24-29) Inside of the 'ngOninit' life cycle method, we try to read the 'id' value from the route using the 'ActivatedRoute.paramMap.subscribe()', then we are invoking our get API call.
  • (Line: 31-35) Invokes the API call by 'id' value, on successful the response will be assigned to 'formFruit' variable, so that data gets rendered on the form.
  • (Line: 37-47) Invokes the update API, on success navigate back to the 'HomeComponent'.
Add the following HTML code to the 'edit.component.html'.
src/app/fruits/edit/edit.component.html:
<div class="container">
    <legend>Edit Item</legend>
    <form>
      <div class="mb-3">
        <label for="txtName" class="form-label">Name</label>
        <input type="text" name="name" [(ngModel)] = "fruitForm.name" class="form-control" id="txtName" />
      </div>
      <div class="mb-3">
        <label for="txtPrice" class="form-label">Price</label>
        <input type="number" name="price" [(ngModel)] = "fruitForm.price" class="form-control" id="txtPrice" />
      </div>
      <div class="mb-3">
        <label for="txtQuantity" class="form-label">Quantity</label>
        <input type="number" name="quantity" [(ngModel)] = "fruitForm.quantity" class="form-control" id="txtQuantity" />
      </div>
      <button type="button" (click)="update()" class="btn btn-primary">Update</button>
    </form>
</div>
Add the edit button in 'home.component.html' file
src/app/fruits/home/home.component.html:
<!-- existing code hidden for display -->
<tr *ngFor="let item of allFruits">

	<td>
	  <a class="btn btn-primary" [routerLink]="['/fruits/edit', item.id]">Edit</a>
	</td>
</tr>
  • Here we use 'routerLink' inside of  '[]' if the URL has a dynamic parameter. On render URL generated as eg:- 'fruits/edits/1'
(Step 1)

(Step 2)

(Step 3)

Delete Operation:

Let's implement delete API logic in 'FruitService'.
src/app/fruits/fruits.service.ts:
delete(id:number){
   return this.http.delete<Fruits>(`http://localhost:3000/fruits/${id}`);
}
  • The 'HttpClient.delete()' invokes the Http Delete request.
Let's update the 'home.component.ts' file as below.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

declare var window: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  allFruits: Fruits[] = [];
  deleteModal: any;
  idTodelete: number = 0;

  constructor(private fruitService: FruitsService) {}

  ngOnInit(): void {
    this.deleteModal = new window.bootstrap.Modal(
      document.getElementById('deleteModal')
    );

    this.get();
  }

  get() {
    this.fruitService.get().subscribe((data) => {
      this.allFruits = data;
    });
  }

  openDeleteModal(id: number) {
    this.idTodelete = id;
    this.deleteModal.show();
  }

  delete() {
    this.fruitService.delete(this.idTodelete).subscribe({
      next: (data) => {
        this.allFruits = this.allFruits.filter(_ => _.id != this.idTodelete)
        this.deleteModal.hide();
      },
    });
  }
}
  • (Line: 5) Declare window variable type.
  • (Line: 14) The variable 'deleteModal' to store the instance of the botstrap modal.
  • (Line: 15) The variable 'idToDelete' to store the 'id' value of the item to be deleted.
  • (Line: 20-22) Assign the bootstrap modal instance to our 'deleteModal' variable.
  • (Line: 33-36) The 'openDeleteModal()' method gets invoked by clicking the delete button. Here we open the delete confirmation modal.
  • (Line: 38-45) The 'delete()' method invokes the delete API call on the success we will hide our bootstrap modal and also exclude the item from the 'allFruits' variable.
Let's add 'Edit' button and 'Delete Confirmation' bootstrap modal HTML code to 'home.component.html'
src/app/fruits/home/home.component.html:
<!-- existing code hidden for display purpose -->
<div class="container">
  
  <table class="table">
   
    </thead>
    <tbody>
      <tr *ngFor="let item of allFruits">
        <td>
          <a class="btn btn-primary" [routerLink]="['/fruits/edit', item.id]">Edit</a> |
          <button type="button" (click)="openDeleteModal(item.id)" class="btn btn-danger">Delete</button>
          </td>
      </tr>
    </tbody>
  </table>
</div>


<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Warning!</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Are you sure to delete the item?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-danger" (click)="delete()">Confirm Delete</button>
      </div>
    </div>
  </div>
</div>
  • (Line: 11) Edit button registered with 'openDeleteModal()' for click event.
  • (Line: 20-36) Delete confirmation bootstrap modal, here we have to give 'id' attribute, based on that 'id' attribute we create the bootstrap instance in 'home.component.ts' file.
  • (Line: 32) Here 'Confirm Delete' button registered with 'delete()' method for click event.

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on Angular 14 CRUD. using I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:


Comments

  1. Great tutorial. There are some minor edits needed in the code, but everything works and I learned a lot. Thank you.

    ReplyDelete
  2. Gracias!! gran tutorial, si bien falto un poco aclarar que el Home se le integra codigo, todo quedo clarisimo!!

    Great Job!!

    ReplyDelete
  3. Thank for the tutorial, great job!

    ReplyDelete
  4. Thanks for this tutorial guide

    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

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