Angularjs – EngineerBabu Blog https://engineerbabu.com/blog Hire Dedicated Virtual Employee in Any domain; Start at $1000 - $2999/month ( Content, Design, Marketing, Engineering, Managers, QA ) Tue, 11 May 2021 13:02:28 +0000 en-US hourly 1 https://wordpress.org/?v=5.5.11 Why is ReactJS the Perfect Choice for Web App Development? https://engineerbabu.com/blog/why-reactjs-is-the-perfect-choice-for-web-app-development/?utm_source=rss&utm_medium=rss&utm_campaign=why-reactjs-is-the-perfect-choice-for-web-app-development https://engineerbabu.com/blog/why-reactjs-is-the-perfect-choice-for-web-app-development/#boombox_comments Tue, 09 Mar 2021 14:23:35 +0000 https://engineerbabu.com/blog/?p=19043 Front-End Web App Development is witnessing a tectonic shift towards ReactJS adoption. Not long ago in the year 2013, Facebook released ReactJS as a JavaScript library for web front-end development. Over the years ReactJS has become one of the most preferred JS frameworks and it is here to stay. In this article, we will outline...

The post Why is ReactJS the Perfect Choice for Web App Development? appeared first on EngineerBabu Blog.

]]>
Front-End Web App Development is witnessing a tectonic shift towards ReactJS adoption. Not long ago in the year 2013, Facebook released ReactJS as a JavaScript library for web front-end development. Over the years ReactJS has become one of the most preferred JS frameworks and it is here to stay. In this article, we will outline the reasons for the landslide victory of ReactJS over its competitors and the benefits of choosing this framework for web app development.

What is ReactJS? 

ReactJS is a JavaScript library, which is easy to learn, reusable, fast, and responsive. It is touted to be the best option for building single-page applications of any scale and size. With all these attributes playing out in its favor, ReactJS is all set to dominate the developer community, job market, and technology landscape.  Data suggests that ReactJS adoption is nothing less than a wildfire. With a lot of big names under its belt who have already migrated or in the process the growth rate of ReactJS is likely to only go higher in the coming years. Besides Facebook, React JS is used by digital pioneers like Uber, Airbnb, Netflix, Amazon, Instagram, Twitter, Shopify, Microsoft, WhatsApp, Atlassian, Codecademy, Dropbox, New York Times, Asana, Intercom, Slack, Storybook… the list goes on. 

Furthermore, ReactJS is among the Top 5 Digital Skills that companies are looking for when hiring developers. The open positions for ReactJS developers grew by a whopping 184% last year compared to 2019. Smart developers know this and are fortifying their skills with ReactJS.  According to Statista, JavaScript is a choice of 67% of developers, and ReactJS is the first choice of developers between all the JS frameworks.

web app development

Data doesn’t lie: ReactJS- Most Used & Loved Framework

To put it in simple words, front-end developers just love ReactJS. In fact, in a recent survey done by Stack Overflow ReactJS was voted as the most loved framework by developers.

web app development

Another report suggests that over 71% of developers who have used ReactJS want to use it again.

reactjs app development

According to the below chart from the State of JavaScript report, which shows each technology’s ratio of satisfaction over its user count, in four quadrants: 

  • ASSESS Low usage, high satisfaction, worth keeping an eye on. 
  • ADOPT High usage, high satisfaction, technologies safe to adopt. 
  • AVOID Low usage, low satisfaction, Technologies to avoid
  • ANALYZE High usage, low satisfaction, Reassess, is already using it. 

ReactJS falls under the ADOPT quadrant (High usage, high satisfaction. technologies safe to adopt). It is not a surprise that ReactJS has garnered 164.1K GitHub stars by the developer community. At the same time, over 9000 companies use the framework in their tech stacks.

web app development

ReactJS- Raging Popularity as Web App Development

Before anything else, let us answer the big question –  what are the factors behind the raging popularity of ReactJS? 

1. Very Easy to Get Started

Thanks to its simple design, use of JSX which is very HTML-like syntax for templating, and highly detailed documentation. Add a small little code generator to the mix and things start to fly, isn’t it? 

2. Reusable Code

Developers spend more time writing JavaScript business logic rather than worrying about the framework-specific code.

3. Fast and Responsive

Owing to the virtual DOM implementation and various rendering optimizations the memory data structures in ReactJS are converted to components. These ReactJS components update and modify the browser by running the computation tasks. VDOM renders these components, data, and elements so that they can be processed and utilized further.

4. Server-Side Rendering

Great support for server-side rendering, making it a powerful framework for content-focused applications. fewer browser compatibility issues, data security, and less loading time. 

5. One-way Data-Binding

Redux, the most popular framework for managing application state in React, is easy to learn and master. Some values can be passed as components and rendered in HTML tags as properties. But, it is difficult to change and access them directly. However, ReactJS allows developers to access components and directly change them by enabling the call back function. This ReactJS property is referred to as properties flow down and actions flow up. 

6. Type Safety

Microsoft’s TypeScript or Facebook’s Flow has native support for JSX and can help in making applications type-safe.

7. SEO Friendly

Applications built on ReactJS are SEO friendly, helping in higher discoverability and visibility of the apps.

8. Native Applications

ReactJS lets developers build Native Mobile Applications by reusing code-With ReactJS you can, not only build high-end Web Applications but also develop Native Mobile Applications (iOS and Android), by using the same code which can be modified with the help of React Native. 

Benefits of Choosing ReactJS vs AngularJS or Vue.js

There are approximately 24 JS frameworks. Most popular being ReactJS, AngularJS and Vue.JS. So, how does ReactJS compare to AngularJS and Vue.js? Here’s a quick overview:

AngularJS

 Angular is the oldest in the race for JavaScript MVVM framework, founded in 2009, which is awesome for building highly interactive web applications. So, you can also hire AngularJS developers to fasten your development work. 

Benefits of AngularJS 
  • Angular is created to be used alongside Typescript and has exceptional support for it. Thus, the strong type support makes the framework pretty robust to work with. 
  • AngularJS boasts of some new features like Angular-based npm libraries from CLI, generation and development of Angular-based Web Components, etc.
  • AngularJS has detailed documentation that empowers the developers with all the necessary information.
  • It enables singular behavior i.e., one-way data binding, thus the app resulting in minimized risks of errors. 
  • The MVVM model (Model-View-View Model) enables developers to use the same set of data and work independently on the same section of the app.
  • Dependency injection of the features related to the components with modules and molecularity in general.
  • The AngularJS structure and architecture is specifically designed for enhancing scalability of flexible projects.
Drawbacks of AngularJS: 
  • It can be difficult to learn in comparison to the other options in the comparison. 
  • Relatively slower performance, according to different benchmarks. 

AngularJS vs ReactJS

  • ReactJS supports Unidirectional data binding and AngularJS support Bi-directional data binding.
  • Compared to ReactJS, AngularJS is difficult to understand. The reason is the support of third-party syntax and libraries.
  • ReactJS is an Open Source Framework while AngularJS is an MVC framework.
  • ReactJS works on Virtual DOM and AngularJS works on Regular DOM.

Vue.JS 

Vue.js, a JavaScript framework, was launched in 2013. It is a flexible framework with advanced web tools to develop modern SPAs (single-page applications) and front-end web apps.

Benefits of Vue.JS: 
  • Detailed Documentation-  Vue.js has very clear documentation which can shorten the learning curve and makes it easy to start. 
  • Familiar Interface- It provides a rapid switching period from other frameworks to Vue.js because of the similarity with other frameworks. 
  • Better Integration- This framework can be used for developing both single-page applications and also complex web app interfaces. 
  • Focus on scaling to develop pretty large reusable templates. 
  • Tiny size- Vue.js is a lightweight framework of around 20KB.  As a result, it is a fast and flexible framework that allows for efficient performance.
Drawbacks of Vue.JS: 
  • A small developer community and lack of support make it hard for developers to find solutions to problems.
  • While enterprises like Xiaomi and Alibaba have adopted Vue.js and it has helped in popularizing the framework. The popularity ratio remains higher in China and a major part of the content and discussion around the framework is in Chinese.
  • Vue.JS has a two-way data binding for managing DOM updates. The issue with the reactivity system is that it renders only the chunks of data that were triggered and often makes mistakes during data reading, which requires data to be flattened.

 Vue.JS vs ReactJS 

  • Vue uses HTML templates while React uses JSX. JSX or JavaScript Expressions is integration of CSS and HTML into JavaScript. It is an XML-like syntax that enables developers to develop UI components that are self-contained along with view-rendering instructions.
  • Apps built on React have faster performance than the ones built on Vue. The addition or extension of a component makes the Vue app slower to load.
  •  ReactJS caters to the view layer of an application that is made up of components and Since doesn’t have a built-in architecture pattern. Vue follows the View Model approach and undertakes the pattern on MVVM especially while developing a large-scale application.
In Conclusion:

A lot of factors are involved while choosing the best framework for web app development. Speed, performance, stability, affordability are a few variables that make ReactJS a perfect choice for the development of web apps, especially for large-scale enterprises. No wonder, even giants like Twitter, Instagram, Netflix, trust this framework.  These frameworks are evolving at a faster rate and are in close competition with each other. For the success of any app, the best technology and design have to come together.

Given the ever-evolving landscape of technology it can be difficult for enterprises to have skilled resources in all these areas. However, a staff augmentation partner like EngineerBabu can help you find the best developers across technologies and skills. We work with our customers and support them at every step of the way to ensure a great experience at very competitive pricing. Connect with us.

The post Why is ReactJS the Perfect Choice for Web App Development? appeared first on EngineerBabu Blog.

]]>
https://engineerbabu.com/blog/why-reactjs-is-the-perfect-choice-for-web-app-development/feed/ 2
What is better React or Angular for App Development? https://engineerbabu.com/blog/what-is-better-react-or-angular-for-app-development/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-better-react-or-angular-for-app-development https://engineerbabu.com/blog/what-is-better-react-or-angular-for-app-development/#boombox_comments Thu, 18 Jun 2020 17:43:42 +0000 https://engineerbabu.com/blog/?p=17844 React vs. Angular has been the most popular debate in the developers’ community and clients are troubling to choose the front end development framework in the market today. There are tons of articles titled ‘React vs. Angular‘ or ‘React vs. AngularJS‘ on so many web pages the internet, but most of them lack what the...

The post What is better React or Angular for App Development? appeared first on EngineerBabu Blog.

]]>
React vs. Angular has been the most popular debate in the developers’ community and clients are troubling to choose the front end development framework in the market today. There are tons of articles titled ‘React vs. Angular‘ or ‘React vs. AngularJS‘ on so many web pages the internet, but most of them lack what the readers want to know. In this blog, we have bought you a side-by-side comparison of the frameworks on all the parameters. We will answer the question of what better React or Angular for App development is for you so that you can choose when choosing between the two.

In React vs. Angular, both React and Angular are the powerful development tools used for single-page and multi-page applications, which often connect to external APIs to receive or send data. They have many similarities but some differences too, which makes it a topic of debate that which one is better in React vs. Angular

Source: www.medium.com

Businesses often get into the dilemma of React vs. Angular and find it challenging to choose the right framework for their app. We’re going to check and contrast the two JavaScript frameworks and study each of them to make sure we don’t miss a single piece of data and create a comprehensive and justified choice while choosing a framework. 

In the next 8 to 10 minutes, you’ll know what separates Angular and React from each other, when to choose ‘React’ over ‘Angular’ for app development and the situations where you can benefit from choosing ‘Angular’ over ‘React.’ Let’s end the ‘React vs. Angular’ or ‘React vs. AngularJS’ debate for all. Go ahead and have a happy reading.

  1. Source and Origin:

Angular

Angular is a JavaScript front-end framework which is written in TypeScript, for web and mobile development. It was developed by Google and launched in September 2016. Angular (Angular 2.0) is a complete rewrite of AngularJS (Angular 1.0), which was introduced in 2010, and the latest release took place on June 10, 2020. 

React

React, on the other hand, is a JavaScript library for UI development developed and maintained by Facebook and the community. Jordan Walke is the original author who introduced this framework on May 29, 2013. The last stable release took place on March 19, 2020.

  1. State Management:

An application uses states in multiple instances. A component describes the UI of an application. What framework does is re-rendering the complete component UI when the data changes. Hence, an application ensures that the data is updated in learning about React vs. Angular. 

React

In React’s handling state, it uses Redux as the solution; the disadvantage here is that the state needs to be stored in multiple parts of the app with passing the data manually around different component tree levels. MobX, another solution offered by the state management library, offers storing only the minimal required state, while the rest can be derived.

Angular

While in the case of Angular, the Redux is not used. Component data is stored in component properties. State changes in some parts can be recognized and reviewed, but in a relatively larger application, it’s tough to track multi-directional tree series of updates. NgRx or RxJS libraries can improve the features and make sure that the data flow is unidirectional.

  1. Languages:

React

React framework is based on JavaScript ES6+ combined with JSX script (syntax extension, which makes a JavaScript code resemble that written in HTML). It helps in understanding the code and identifying typos. 

Angular

Angular uses TypeScript, which is a superset of JS explicitly developed for larger projects. The code can navigate easily and typos can be spotted since Typescript is more compact than JavaScript. The code refactoring process also becomes more straightforward and faster. Hence, developers can write cleaner codes.

While React allows the reuse of the code components at distinct levels making it easier to manage the updates; Angular helps developers to write cleaner codes with the more compact Typescript. 

  1. App Structure:

Angular

AngularJS comes with a fixed and complex structure consisting of three layers: Model, View, and Controller. It is suitable for experienced developers only. The framework allows developers to break down the app’s code in different files. The files’ links are written in the app directive, which displays the app’s structural logic. Respectively, Angular components are also reusable.

React

The best thing about the structure of React is that there is no “the only right structure.” Developers have the freedom to choose. Every pro has its following con. Having a no fixed structure makes it challenging to design one at the start of each project. React app has a component-based architecture; the components make the code, which is then rendered with the React DOM library. The rendered code is then directed in two ways; functional and class-based.

In React, reusing the existing code allows the developers to apply faster reloading into the process, improving the app performance and enhancing the development speed. The React framework gives you the freedom and flexibility to choose the suitable tools, libraries or repositories, and the architecture or structure for app development. React enables you to build a highly-customized app using only the features and tech stack you require.

5. DOM (Document Object Model):

Angular

Angular uses real DOM, where even if one section of it is altered, the whole tree data structure is updated.

React

On the other hand, React app development uses Virtual DOMS. Since they are lightweight and built on the server, they reduce the browser load. App development companies can easily track and update changes to the VDOM without affecting any other section of the tree data structure. 

Since Virtual DOM is also vastly considered much faster in performance than real DOM, it makes it much better for app development. This is the reason, in React vs. Angular, React ranks over Angular in the context of Document Object Model.

6. Testing:

Angular

Angular provides developers the simplicity of using one tool for the entire project’s testing. Developers use industry-standard tools like Jasmine and Protractor.

React

React requires the use of different tools for different kinds of tests. Developers have to use various tools for different types of testing, like Render testing, Code Testing, component testing, and unit testing. It increases the overall timeline of the app development process and requires more effort from the developer’s end.

Hence, Angular wins the React vs. Angular debate in terms of testing.

7. Learning Curve:

Angular

Angular has a steep learning curve due to its vast library, and learning all the concepts takes much more time as compared to the React. Angular IO framework offers different ways to solve a specific problem. It has a complex component management system, and it is essential for developers to be familiar with different concepts and languages like TypeScript, templates, dependency injection, RxJS, etc.

The framework core embeds some complicated features, which limits developers to use them before learning them. Besides, the framework is continuously developing – making it essential for the developers to check out the latest Angular ecosystem updates and upgrade their skill set accordingly.

React

React is minimalistic: no vast library, no dependency injection, no classic templates, no overly complicated features. Though it might take some time to learn how to set up a project because there is no predefined project structure, yet it’s worth it as the overall development cycle is reduced. Prior knowledge of JavaScript makes the framework simple to understand. It would be helpful if developers learn the Redux library, which is used in more than half of React applications for state management. 

Source: www.inflexion.com

Reactjs allows you to quickly learn and develop a mobile app in the React framework if you are well-versed in JavaScript. ReactJS provides various constructive resources and assets to the developers to get familiar with the framework and develop an application with the same. It is for these reasons; developers tend to choose to React over Angular. So it’s clear that in React vs. Angular based on the Learning Curve, React is better than Angular.

Source: www.edureka.com

  1. Data Binding:

React

React uses one-way data binding in which allows the UI elements to be changed only when the model state is being changed. The developers’ limitation using React is that they cannot alter the UI elements without updating the corresponding model state.

Angular

Whereas, Angular uses a two-way binding approach for mobile app development. Bidirectional data-binding negatively affects the performance of Angular apps. The reason being, each of the binding is assigned a watcher to track changes, and each loop continues endlessly until all the watchers and associated values are checked. Hence, more bindings create more watchers, making the whole process cumbersome. The only good thing about the bidirectional approach is that model state changes automatically with the changes in UI elements and vice-versa.

Angular’s approach might seem easy and productive, but in the long run, React offers a streamlined data overview of larger app projects. Thus, in the context of Data Binding, React wins over Angular in the React vs. Angular debate.

9. Development Speed and Productivity:

Angular

Due to its CLI, Angular offers better development experience – and empowering the creation of a workspace and design functioning applications. Angular focuses on producing components and services with one-line commands, built-in process to solve comprehensive problems and clean coding features.

React

In the case of React, the development speed and productivity are affected by third-party libraries’ involvement. The React JS app developers need to put extra time in determining the right architecture for the app, along with the component tools. 

The toolkit for React mobile app development varies from one project to another; it means more time is consumed if the project is to be handed over to new developers for new updates.

Hence, in React vs. Angular, Angular takes over React in development speed and productivity.

10. UI Components:

React

There are many free as well as paid UI components developed by the community on the React portal. The problem with React lies in the installation of an additional library to use material design components to React. Material-UI Library & Dependencies make React a less preferable choice for app development in terms of UI components.

Angular

Angular is embedded with a built-in Material toolset, which offers a wide variety of pre-built material design components for app development. There are various layouts, buttons, pop-ups, indicators, and form controls. This makes the UI configuration simpler and faster.

Angular clearly wins the ‘React vs. Angular’ war when it comes to UI components.

11. Self-Sufficiency:

React

React is a framework for UI development, which isn’t self-sufficient in itself. Apps written with the React framework requires additional libraries as well. Redux, React Router, or Helmet revamp state management processes, routing, and API interaction. All these functions, like component-based routing, data binding, dependency injection or project generation, couldn’t work without installing additional libraries or modules.

Angular

Angular, on the other hand, is quite a self-sufficient framework for app development. It generally does not need additional libraries or modules to carry out some of its essential functions. The angular package comes as a full-fledged package. The functions like component-based routing, data binding, form validation, project generation, and dependency injection – can be implemented within the Angular package without installing any additional libraries. 

When it comes to React vs. Angular, the latter is a complete software development framework in itself that does not require the inclusion of any additional library. Therefore, the vote goes to Angular in terms of Self-sufficiency.

12. Directives:

React

React gives relief by explaining templates and logic at one place – at the end of the component. The best thing about React is that logic and templates in React are explained at the end of every component. This facility enables the readers to understand the meaning of the code even without having to know its syntax. 

Angular

In the case of Angular, the syntax is complex, and it makes it difficult for a reader to comprehend who doesn’t have any prior experience working with this technology. Under Angular, each template is returned with an attribute – a directive of how the object has to be set. 

The complex syntax of Angular’s makes it incomprehensible for the new developers, and therefore in React vs. Angular comparison React is preferred over Angular when it comes to directives.

13. Popularity:

As per Google Trends, React has more searches than Angular. While people show more interest in Angular due to the availability of ample ready-made solutions, both the technologies are developing, which means both are popular in the market. So for now, the answer to Angular vs. React popularity would be equal on both sides, i.e., Angular popularity = React popularity (at least in the current time). 

React

React is an extensively used framework, used for software development (both web and mobile app). However, Mobile app development requires it to be incorporated with Cordova. 

React is known for its multiple uses; for example, it can be used to build both single-page and multiple-page web applications. Moreover, for mobile app development, there is an additional framework – React Native.

Angular

Angular is suitable for web and mobile app development. Ionic has done a significant amount of work in mobile development. Similar to React, Angular can also be used for both single- and multiple-page web apps. Angular also has an additional mobile development framework, which is NativeScript.

Hence, it’s tough to choose a real winner between React vs. Angular, and we will call it a draw situation.

14. Toolset:

React

React uses multiple code editors like Sublime Text, Atom, and Visual Studio. It uses the Create React App (CLI) tool for bootstrapping a project, while the server-side rendering is done with Next.js framework. For testing the app written in React, calls for multiple tools for different elements. 

Angular

Angular, like React, also uses different code editing tools like Sublime Text, Aptana, and Visual Studio. The project is set up using Angular CLI, while the server-side rendering is done through Angular Universal. 

The Angular IO testing and debugging for a complete project are possible with a single tool like Jasmine, Protractor and Karma. But, this is not possible in the case of React js app development. A set of tools is required for performing different sets of testing.

For example, you will require Jest JavaScript code testing, Enzyme and Unexpected-React for component testing, Skin-deep for Render testing utils, React-unit for unit testing, and so on. This increases the efforts and time required in the testing process.

But the point of difference between Angular and React technology is that Angular can be tested entirely with only one tool. It can be either Karma, Protractor, or Jasmine. It is also one of the unique Angular advantages over React. So, the winner of this React vs. AngularJS war is Angular.

15. Community:

React

In React vs. Angular, React is one of the most popular JS frameworks globally, and there is a large community of developers developing it and using it for app development. Working with React, you have to be an active learner since the framework is continuously evolving, and new updates are being released.  

Keeping pace with all the changes is sometimes difficult, even when the community moves forward with the latest documentation. The community support on thematic forums helps in solving the issue of lack of documentation. 

Angular

Angular, on the other hand, has less community support than React. It faces a lot of cynicism, partially due to the low popularity of Angular 1.0. Due to its steep learning curve, developers used to dismiss the framework as a complex framework. What works in building Angular’s reliability is that the framework has been developed by Google. 

Google acts as a godfather and provides all-time support to the framework and reiterates it. Documentation often falls behind because of its continuous updates.

GitHub is the most popular community network by developers, coders and React has much broader community support than Angular on GitHub and GitLab. This upholds React at a slightly higher position than Angular when it comes to community support.

To wrap it up, it’s quite clear from the benefits point of view, in the React vs. Angular war, React has won by more no. of votes. Higher community support, more popular, customizable, flexible, more comfortable to learn, and to top faster development cycle makes React a preferred framework for app development. 

React vs. Angular: The Brand Game

Before you make your choice for framework between React vs. Angular, take a look at which are the brands that use React and the ones which use Angular. 

React vs. Angular: The Brand Game

Source: www.google.com

So, now you know the advantages and disadvantages of both the front-end frameworks, you can better decide on which framework you would like to develop your app based on your project. We have expert React and Angular developers, which you can hire directly. Hire React developers from EngineerBabu and get started with building an excellent app for your business. If Angular developers are more suitable for your project, then hire dedicated Angular developers who are experienced and knows how to build an app that gets a million downloads. If you any questions, feel free to reach out to us and discuss your idea. Don’t you worry, your idea is well protected under NDA. So, what are you waiting for? Hire dedicated developers now. EngineerBabu is known for delivering world-class products and giving the clients more than their expectations.

The post What is better React or Angular for App Development? appeared first on EngineerBabu Blog.

]]>
https://engineerbabu.com/blog/what-is-better-react-or-angular-for-app-development/feed/ 0
Angular Authentication Using JWT https://engineerbabu.com/blog/jwt-authentication/?utm_source=rss&utm_medium=rss&utm_campaign=jwt-authentication https://engineerbabu.com/blog/jwt-authentication/#boombox_comments Fri, 25 Jan 2019 13:14:24 +0000 https://www.engineerbabu.com/blog/?p=13230 Building a web-based product is not just a skill anymore; it’s a necessity, for anything and everything that requires public attention. A decade into the digital revolution, we are finally witnessing a tectonic shift in users’ behavior towards consumer products, wherein a majority of these products are either web-applications or mobile-applications. A web/mobile app is...

The post Angular Authentication Using JWT appeared first on EngineerBabu Blog.

]]>
Building a web-based product is not just a skill anymore; it’s a necessity, for anything and everything that requires public attention.
A decade into the digital revolution, we are finally witnessing a tectonic shift in users’ behavior towards consumer products, wherein a majority of these products are either web-applications or mobile-applications.
A web/mobile app is usually a culmination of many components working in unison. One of the most overlooked, but significant part is user authentication. Believe me, when I say this, 70% of users leave the platform if they aren’t satisfied with the on-boarding experience.
It HAS to be Smooth & Simple.
There are countless tutorials out there exhibiting  code of how authentication in angular works, some even go the extra mile to explain how the code runs, but the only issue with such codes (for rookies) is the flowery words and jargon they use, which can be quite troublesome for someone who is just starting-out in the domain.
The following is a detailed, yet simple guide on how authentication works in angular. The code for the same could be found here. The following code is well commented so that you understand what is actually happening!

This tutorial is not a step by step guide to authentication with angular. The Internet is already swarming with thousands of them, but what’s missing is a detailed explanation of the working of those steps.

How to Authenticate Angular using JWT

It is recommended that you clone the project hereand go through this tutorial while referencing the code. It will give you the clarity you are yearning for…
Before we start with the “coding” section, we need to understand the basic concept behind authentication and JSON Web Tokens (or JWT as millennials call it).
Authentication is a means of verifying the identity of a user, which means if the user is allowed to access the application or not.  The two most prevalent ways a user can get authenticated is either through social login (Google+/Facebook login) or through a registered username (can be an email) and password. We will be using the latter to understand the inner workings of authentication in angular.
Recommended Read: A Detailed Guide to CSS Animations and Transitions
The codebase for this tutorial works on the following components:

  1. JSON Web Token
  2. Client + localStorage
  3. Backend + Secure API Endpoints + DB
  4. Authentication Service
  5. User Service
  6. JWT Interceptor
  7. Auth Guard
  8. Error Interceptor

After understanding the 8 elements mentioned above, you will not only learn about the workings of JWT and authentication but will also be able to appreciate the process behind it.

  1. JSON Web Tokens (JWT)

JSON Web Tokens, if defined abstractly, is a JSON object which helps in exchanging information between two or more parties securely. In layman terms, it’s a type of validation token from the authentication server, which indicates that the username and password supplied by the user at the time of logging in whether it is correct or not, and thus the user is “authenticated”.

Read more about JWT and its intricacies right here.

  1. Client + localStorage

The client here is the user operating on a browser (Google Chrome/Firefox/Opera/Safari). For every registered user, there is a set of username and password stored in the database at the backend.

The two most important types of storage properties of any browser are the localStorage and the sessionStorage; they allow you to store key-value pairs in the browser.

  • localStorage
    It is a persistent storage option when you don’t want the user to be logged out on refresh or closing of a browser tab. The localStorage stores the data without expiration date by default. It is a read-only property.
  • sessionStorage
    As the name indicates, it stores data for a particular session only. It is less persistent, and the user data gets lost on the closing of the browser tab or refreshing.

We will be using localStorage in our case.
NOTE: One can find localStorage in the developer console (F12 on Chrome) under the “Application” tab.
local storage

  1. Backend + Secure API Endpoints + DB

The backend for this tutorial is a fake backend as we just want to understand how things are working on the front-end part. But this backend works as any real backend wherein it has API’s that provide us with a response body and response status. The fake-backend.ts also has test data (DB) for a test user. The credentials input by the user will be validated against this test data.

Test Data:
test dataThe fake-backend will serve as a standalone backend with a delayed response so that it can imitate a real backend. The two major tasks it will perform are:

  1. It will check the user credentials that come from “Authentication Service” during login
  2. It will also work as a fake database keeping the user details (hitting a secure API end-point). The user can request for the user details only when the requests have valid JWT Token in its request authorization header

The two API’s that our current backend has are:

  • To check credentials – /users/authenticate
    If the user credentials match the test user stored data, the backend sends a response body with a JWT token.

fake-backend.ts

API to check credentials

  • To give back user details – /users
    This is a SECURE API endpoint. By secure, it means that to access this API endpoint, the request must have a valid JWT Token with it. This token is in the request header with the “Authorization: Bearer JWT-TOKEN” property.It first checks for a valid JWT token and then it responds accordingly.

fake-backend.ts

API to give back user details

  1. Authentication Service

Authentication Service

Authentication service is used to LOG IN and LOG OUT from the application. It possesses the credentials (username and password) from the client (user/browser) to the backend and checks for the response, if it has JWT token.

If the response from the backend has a JWT token, then the authentication was successful. On successful authentication, the user details are stored in the local storage along with JWT token.

JWT token

  1. User Service

The user service is a service dedicated to hitting the 2nd API (the secure API end-point) to fetch the data for all the users present in the database. Currently, only a single user is present – test user. This User Service is accessed via the home component as soon as the user logs in and the home component is initialized.

  • home.component.ts

home component
The service will get the response from the backend only if the backend receives the request along with a valid JWT token.

  • user.service.ts

user service
The token is not sent when the request by the client is made. Here is when JWT Interceptor comes to rescue!

  1. JWT Interceptor

JWT Interceptor

The JWT interceptor intercepts the incoming requests from the application/user and adds JWT token to the request’s Authorization header, only if the user is logged in (because then the JWT token will be present in the localStorage at client’s end).

The JWT interceptor works very smarty by not modifying the original request made by the user service, but cloning the request and adding the JWT token to the request header and then forwarding the cloned request to the backend. The value of the token is fetched from the client’s localStorage. If the user is logged out, there will be no JWT token in the localStorage, and thus, the user won’t be able to access the secured API endpoint.

jwt.interceptor.tsJWT Interceptor

  1. Auth Guard The Auth Guard works as umm – a Guard!

The auth guard ensures that only authenticated users access specific routes in the application. The auth guard implements an interface called CanActivate with the help of which it returns either true or false.

True If the user is logged in, i.e. the localStorage has current users’ details along with a valid JWT token

False If the user is logged out, i.e. the localStorage lacks the current user details along with a valid JWT token, and in turn, will then redirect the user to the login page.

auth.guard.ts
Auth Guard

In this particular example, we are using the presence of the current user detail as a way to give rights to access one specific route, i.e. ‘/’ (root), or the HomeComponent. There can be other conditions too like role-based authentication. The rights to access particular routes will then be allocated on the basis of the role of a specific user. The user will be able to access the admin route (say) only if he is an admin.
Even though it is developed in a separate file auth.guard.ts, but it is implemented in the routing of the application, with the canActivate parameter.
app.routing.ts
App Routing

  1. Error Interceptor

The HTTP error interceptor works with the calling service and the API’s

It intercepts the responses from the API and checks for the status codes (if there were any errors).

Error Status

  1. 200: Success
  2. 401: Unauthorized Response – the user will be automatically logged out

All other errors are RE-THROWN, to be caught by the calling service so an alert can be displayed by the user service/component on the client’s end.
error.interceptor.ts
Error Interceptor


Wrapping Up

The thing about angular (or any framework) is – The more you work with it, the more you’ll discover what all you don’t know. The lack of knowledge about fundamentals will prove to be a hindrance and in turn, will slow down the development process. This is my effort to make one of the components of a web-app development process, i.e. Authentication – EASY!

We hope you found this post valuable. In case you have any doubts, let us know in the comments below.


Recommended Read:

The post Angular Authentication Using JWT appeared first on EngineerBabu Blog.

]]>
https://engineerbabu.com/blog/jwt-authentication/feed/ 3