Categories
frontend javascript

5 Frontend Development Trends to follow in 2022

Hey everyone 👋🏻,

In this article, let us discuss about Top 5 Frontend Development Trends to follow in 2022

1. JavaScript

JavaScript is one of the most popular programming languages that you can learn these days. More than 70 percent of the websites are developed using JavaScript. It is continually evolving as more and more features are getting introduced into the language. JavaScript is the language that powers the web and is one of the top most tools that big companies are using these days.

There are currently 1.4 million JavaScript libraries that can be used by web developers across the world. In addition, web browsers now feature a separate JavaScript engine that speeds up these computations, resulting in faster page load times. JavaScript is a constant trend in front end development with a plethora of libraries.

Image description
Source

2. JAM Stack

JAM Stack is not a technology or language but an architectural design that uses JavaScript, APIs, and Markup. These individual technologies can be combined to produce a decoupled web application whose front-end and back-end are separated. JAM Stack boasts of providing following benefits to websites and project workflows : Security, Scale, Performance, Maintenance, Portability and Developer Experience

Image description
Check the website : https://jamstack.org

3. Micro-frontends

Image description

The term Micro Frontends first came up in ThoughtWorks Technology Radar at the end of 2016. It extends the concepts of micro services to the frontend world. The current trend is to build a feature-rich and powerful browser application, aka single page app, which sits on top of a micro service architecture. Over time the frontend layer, often developed by a separate team, grows and gets more difficult to maintain. That’s what we call a Frontend Monolith.

The idea behind Micro Frontends is to think about a website or web app as a composition of features which are owned by independent teams. Each team has a distinct area of business or mission it cares about and specialises in. A team is cross functional and develops its features end-to-end, from database to user interface.

Source

4. React.js

Image description

React.js is one of the most popular JavaScript libraries for building modern and sleek user interfaces these days. It does not need an introduction as such because it is that popular that almost every new developer these days is learning React. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

Image description
Source : https://www.npmtrends.com/react-vs-vue-vs-@angular/core

5. Progressive Web Applications

Image description

The idea behind Progressive Web Applications is to provide a native app experience to the user through the browser itself. PWAs are extremely beneficial as they are of lesser size (in KBs) and provide a near-similar experience like a native application. You would often see PWAs are released as “Lite” versions on the play store and do not exceed 1 MB in size. Even though it looks like a native app, it opens up a browser inside to view the items.

Progressive Web Apps (PWAs) are web apps that use service workers, manifests, and other web-platform features in combination with progressive enhancement to give users an experience on par with native apps.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
python

Build your own J.A.R.V.I.S in Python [Full Code + Video]

In this article, we will learn how to create a Feature Rich Virtual Assistant in Python. We will be adding following features to this project :

1. Time Reporting

2. Taking Screenshot

3. Performing Google Search

4. Opening a Specific Website

5. Searching on Wikipedia

6. Listen to Jokes

7. Desktop Notifications for COVID-19 Statistics.

Here is the code for the complete project :

import speech_recognition as sr
import pyttsx3
import datetime
import webbrowser
import wikipedia
import pyjokes
import pyautogui
from plyer import notification
from bs4 import BeautifulSoup
import requests

engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)


def input_query():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print('recognition is on....')
        recognizer.pause_threshold = 0.7
        voice = recognizer.listen(source)
        try:
            query = recognizer.recognize_google(voice).lower()
            print('this is the query that was made....', query)
            return query
        except Exception as ex:
            print('An exception occurred', ex)


def report_time():
    current_time = datetime.datetime.now().strftime('%I:%M %p')
    return current_time


def speak_va(transcribed_query):
    engine.say(transcribed_query)
    engine.runAndWait()

def make_request(url):
  response = requests.get(url)
  return response.text

def activate_va():
    user_query = input_query()
    print('user query ....', user_query)
    if 'time' in user_query:
        current_time = report_time()
        print(f"the current time is {current_time}")
        speak_va(f"the current time is {current_time}")
    elif 'open website' in user_query:
        speak_va(
            "Please type the name of the website that you want to open (specify the full url) \n")
        website_name = input()
        print(website_name)
        webbrowser.get(
            'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open(website_name)
        speak_va(f"{website_name} opened.")
    elif 'wikipedia' in user_query:
        speak_va("Searching on Wikipedia")
        user_query = user_query.replace('wikipedia', ' ')
        result = wikipedia.summary(user_query, sentences=4)
        print(result)
        speak_va(result)
    elif 'joke' in user_query:
        random_joke = pyjokes.get_joke()
        print(random_joke)
        speak_va(random_joke)
    elif 'screenshot' in user_query:
        image = pyautogui.screenshot()
        image.save('screenshot.png')
        speak_va('Screenshot taken.')
    elif 'search' in user_query:
        speak_va("What do you want me to search for (please type) ? ")
        search_term = input()
        search_url = f"https://www.google.com/search?q={search_term}"
        webbrowser.get(
            'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open(search_url)
        speak_va(f"here are the results for the search term: {search_term}")
    elif 'covid stats' in user_query:
      html_data = make_request('https://www.worldometers.info/coronavirus/')
      # print(html_data)
      soup = BeautifulSoup(html_data, 'html.parser')
      total_global_row = soup.find_all('tr', {'class': 'total_row'})[-1]
      total_cases = total_global_row.find_all('td')[2].get_text()
      new_cases = total_global_row.find_all('td')[3].get_text()
      total_recovered = total_global_row.find_all('td')[6].get_text()
      print('total cases : ', total_cases)
      print('new cases', new_cases[1:])
      print('total recovered', total_recovered)
      notification_message = f" Total cases : {total_cases}\n New cases : {new_cases[1:]}\n Total Recovered : {total_recovered}\n"
      notification.notify(
        title="COVID-19 Statistics",
        message=notification_message,
        timeout=5
      )
      speak_va("here are the stats for COVID-19")
while True:
    activate_va()

Watch on YouTube

If you want to follow along with me, check the video here :

Follow me on:
👉 Twitter: https://twitter.com/The_Nerdy_Dev
👉 Instagram: https://instagram.com/thenerdydev
👉 YouTube: https://youtube.com/thenerdydev

Categories
frontend javascript vuejs

✨8 Vue Projects Every Beginner Should Try

Hey everyone 👋🏻,

In this article, let us see 8 Vue Projects Every Beginner Should Try.

This article was first published on https://the-nerdy-dev.com/.
Check the website for more interesting articles and tutorials on Web Development.

Introduction

Image description

Vue.js is an open-source model–view–view-model (MVVM) front end JavaScript framework for building user interfaces and single-page applications. It was created by Evan You, and is maintained by him and the rest of the active core team members

1. 6 Hours Vue.js and Firebase Project – FireBlogs by @traversymedia

Learn how to build a multi-user blog project with Vue.js, Vuex and Firebase.

What will you learn?

  1. Vue.js basics and fundmentals
  2. State Management using Vuex
  3. Working with Firebase

2. Build a COVID Tracker App with Vue.js and Tailwind

In this project, Brad uses Vue.js and Tailwind to create a Simple COVID Tracker Application.

What will you learn?

  1. Vue.js Fundamentals and Basics
  2. Working with Tailwind.css

3. Vue.js + Vuetify + Firebase Project – DevMeetup

In this tutorial, Maximilian Schwarzmuller shows how to build a complete Project – a Developer Meetup App – with Vue.js 2, Vuetify and Firebase. This is a 24 part series.

Image description

www.youtube.com/playlist?list=PL55RiY5tL51qxUbODJG9cgrsVd7ZHbPrt

What will you learn?

  1. Vue.js 2 Fundamentals and Basics
  2. Vuetify Components
  3. Working with Firebase

4. Build a Weather App in VueJS | Vue Beginner Tutorial

Learn how to make a Weather app in Vue JS, we use the Open Weather Map API to make calls to a restful api to return the current weather data. This uses the Modern Javascript Fetch API along with Vue JS Methods and conditionals.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Interacting with APIs via API calls.

5. Build a Invoice App With Vue 3, Vuex & Firebase

In this video, we build out a full CRUD (create, read, update & delete) invoice app using Vue 3, Vuex & Firebase.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Working with Firebase
  3. State Management using Vuex

6. Create a Gridsome Portfolio – Vue.js project

Learn how to make a portfolio kind of an application using Gridsome library with Vue.js

What will you learn?

  1. Vue.js basics and fundamentals
  2. Gridsome library

7. E-commerce Website With Django and Vue Tutorial (Django Rest Framework)

Learn how to build an e-commerce website using Django and Vue from scratch. Django uses Python Vue uses JavaScript.

Django Rest Framework is used to build the API and backend.
The frontend is a separate Vue project. To handle the payments, we implement Stripe.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Learn Django to create a full stack application

8. Full Stack Web App in Vue.js & Express.js

Image description
Learn how to build a full stack application using Vue.js and Express.js with Postgres as the database

What will you learn?

  1. Vue basics and fundamentals
  2. Making a full stack application with Vue.js and Express along with Postgres as the database

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
👉🏻 Join our Discord Server : https://discord.gg/fgbtN2a

Categories
css frontend html web development

Web Dev Made Easy

Hey everyone 👋🏻,

In this article, I will tell you about a website using which you can use as a resource for learning Web Development.

So the website name is this :

web.dev

https://web.dev

Image description

Now some of the featured courses on their website are :

Image description

1. Learn Responsive Design

Image description

This course takes you on a journey through the many facets of modern responsive web design. The first few modules will ease you in with a history of where responsive design came from and a look at the fundamentals of responsive layouts. From there, you’ll learn about responsive images, typography, accessibility and more.

Along the way you’ll find out how to make websites responsive to user preferences and device capabilities. By the end, you’ll also have an understanding of what the future might hold for responsive design.

Each module has demos and self-assessments for you to test your knowledge.

This course is created for beginner and intermediate designers and developers. A basic understanding of HTML and CSS should be enough. You don’t need to know any JavaScript. If you’re completely new to making websites, there’s an introduction to HTML and another course to help you learn CSS.

2. Learn Forms

Image description

This course breaks down HTML forms into easy to understand pieces. Over the next few modules, you’ll learn how an HTML form works and how to use them effectively in your projects. Use the menu pane by the Learn Forms logo to navigate the modules.

You’ll learn how to build a basic HTML form, about HTML form elements, styling forms, help users re-entering data, ensuring the form is accessible, and secure, how to test your forms, and about specific form types.

Each module is full of interactive demos and self-assessments for you to test your knowledge.

This course is suitable for beginners and advanced HTML developers. The first few modules help you get started with building HTML forms, the other modules give more detail. You can go through the series from start to finish to get a general understanding of HTML forms, or pick a specific module you want to learn more about.

3. Learn Progressive Web Apps

Image description

This course covers the fundamentals of Progressive Web App development into easy-to-understand pieces. Over the following modules, you’ll learn what a Progressive Web App is, how to create one or upgrade your existing web content, and how to add all the pieces for an offline, installable app. Use the menu pane by the “Learn PWA” logo to navigate the modules.

You’ll learn PWA fundamentals like the Web App Manifest, Service Workers, how to design with an app in mind, what’s different from a classic web app, how to use other tools to test and debug your PWA. After these fundamentals, you’ll learn about integration with the platform and operating system, how to enhance your PWA’s installation and usage experience, and how to offer an offline experience.

Each module includes interactive demos and self-assessments for you to test your knowledge. You will be able to test and try demos on your mobile phone, tablet, or laptop while playing with the code to understand the fundamentals of what makes a Progressive Web App.

This course is created for a beginner and advanced web developers alike. You can go through the series from start to finish to get a general understanding of PWA from top to bottom, or you can use it as a reference for specific subjects. For those new to web development you will need a grounding in HTML, CSS, and JavaScript to follow along. Check out Learn CSS, and the HTML and JavaScript courses on MDN.

4. Learn CSS

Image description

This course breaks down the fundamentals of CSS into digestible, easy to understand pieces. Over the next few modules, you’ll learn how the core aspects of CSS work and how to use them effectively in your projects. Use the menu pane by the “Learn CSS” logo to navigate the modules.

You’ll learn CSS fundamentals like the box model, cascade and specificity, flexbox, grid and z-index. And, along with these fundamentals, you’ll learn about functions, color types, gradients, logical properties and inheritance to make you a well-rounded front-end developer, ready to take on any user interface.

Each module is full of interactive demos and self-assessments for you to test your knowledge. In addition to learning through reading and demos, there is an accompanying podcast episode for each topic as another way to learn and continue expanding your knowledge.

This course is created for beginner and advanced CSS developers alike. You can go through the series from start to finish to get a general understanding of CSS from top to bottom, or you can use it as a reference for specific styling subjects. For those new to web development overall, check out the intro to HTML course from MDN to learn all about how to write markup and link your stylesheets.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
database mongodb

The NoSQL Database : Basics of CRUD in MongoDB – Part 1 – insertOne, find

Hey guys 👋🏻,
In this article, let us understand about The NoSQL Database : Basics of CRUD in MongoDB. So in this article we will learn about how to retrieve to retrieve/access, delete, create and update our documents. We will also see how we can delete a document by making use of its id and all that jazz. We will be covering the basics about collections and documents, the basic data types and we will also see how we can perform these CRUD operations. So without a further ado, let’s get started.

Image description

Database, Collections and Documents

In the MongoDB world, you can have one or more databases. Each database can hold one or more collections. Now what is a collection ?

A collection is just like a table that we have in a relational database like SQL. In a collection that you and I create, we can have multiple documents. Something that we will discuss a bit later.

Now what do we mean by documents ?

A document is essentially a data piece that you store in the database.

You don’t need to worry about these much. When working with MongoDB database, collections and documents gets implicitly created for you when you start storing the data and work with them.

A bit later in this article we will also learn an explicit way of creating documents in your collection using which you can also configure them a bit further.

The Shell and the MongoDB drivers for different languages

You will use MongoDB drivers in the real world applications
depending on the programming language you are using for writing
the backend servers on.

Shell is the only approach that will work for every language.

MongoDB CRUD Operations

Shell is what gets connected to the local mongo server.

Creating Databases and Collections

To check what databases, we have on the server we can run the command :

Now to switch to a database, we can make use of the use command.
If the database exists, then the use command in that case will make use of the existing one otherwise it will create the new one on the fly so basically on the execution of the command. So let us create a database and call it as flights

So to switch to the flights database, we can say :

We store collections in database. But in order to access a document we need to access that respective collection first in which the document resides, then only we will be able to access the document.

Understanding JSON data

Every document you enter gets a new unique id which is the feature
of the MongoDB. You need to have a unique id for each and every document. We do not have to specify it on its own. Mongodb does this for us under the hood which is of type ObjectId which is another type supported by MongoDB. This id will allow you to sort the documents because it has some timestamp associated to it. This is how JSON data gets stored into our database, to be precise into the collection of our database.

To list all the databases that are there on the MongoDB server, we can run the command :

and this would give us something like this :

Now let us switch to the flights database. Now currently as you can see, the flights database does not exists. So to create it on the fly, we can make use of the command use flights and this will automatically generate a flights database for us.

As a result of the above command, we get this as output in our terminal :

switched to db flights

Let us insert a new flight into the flightData collection which gets implicitly created on demand. Now this new flight is a new document which gets inserted in the flightData collection of the flights database which we reference as db. So db here represents the current database to which we are connected to.

Image description

Now on running the above query, we get this as the output :

To display the array of flight documents in a pretty formatted manner.

  1. First we reference the current active database db.
  2. Then reference the collection whose all the documents we want to retrieve which in our case is flightData
  3. The find() method retrieves all the documents in the current referenced collection.

So this is our query for same :

Image description

and this is the output for same :

Let us now do a comparison between JSON and BSON.

Comparing JSON and BSON

This is what JSON looks like :

JSON is what we insert or retrieve. Behind the scenes, MongoDB actually uses BSON data. This conversion is done by the drivers. This is simply done because BSON is more effective
to store than the JSON data, faster and more efficient in terms of size and efficient storage. There are different types of data – numbers, binaries etc. which are stored in different ways behind the scenes

BSON stands for Binary JSON for storing data into the database.

Let us insert one more flight in our flightData collection.

Image description
Image description

This above insertOne does work because the collection
can accept mixed documents since we know MongoDB is schemaless.

Two documents in the same collection don’t necessarily need to have the same schema

We may have the schema but it is not the must.
The id which is autogenerated you just don’t have to use the autogenerated id you just have to ensure that you have a unique id but if you cannot ensure this you can assign the ids on your own.

Let us insert the same document which we inserted which had missing schema with the id of our choice.
Make sure the id that you use is unique.

So here is the query for same. Please note here we are using an id of our choice i.e lmn-kpq:

Image description

After inserting the document into the flightData collection, we can find all the documents within the collection

Image description

Here the id is unique and it is the one that we used while creating the new document. It doesn’t have ObjectId type
for the simple reason because it was not autogenerated by MongoDB it is the id that we gave to the document. In the next article, we will learn more about CRUD operations. See you next time !

Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Categories
backend mongodb

Security and Authentication in MongoDB

Hey guys 👋🏻,
In this article, let us understand about Security and Authentication in MongoDB. We will understand the security aspect from the perspective of developers and NOT for the database admins.

Image description

This article was first published on https://the-nerdy-dev.com/.
Check the website for more interesting articles and tutorials on Web Development.

What are the most important parts for securing the mongodb database ?

Image description

Security Checklist

For hardening the Mongo Environment and making sure that it is safe and cannot be tampered from outside, we need a security checklist.

Authentication and Authorization

The database that we will be using to store data and users will know the users and your code will have to authenticate as a database in order to get data, update data and do all kinds of stuffs with the data that you get back. It is the most important building block for securing your MongoDB environment.

Another important building block is the Transport Encryption

Transport Encryption

This means the data that you sent from your app to the server should be encrypted so that no MAN IN THE MIDDLE attack can compromise your credentials.

Encryption at Rest

This means that the data in the database also should be encrypted otherwise if someone somehow gets access to your database servers well they can then read plain text information easily.

So it is a must to store the data in the database in the encrypted format as well.

Auditing

This is the pure server admin task and not the concern for the developer but Mongodb provides auditing to servers to see who did what and what actions occurred so that you can control and are aware of what is happening inside the database

Server & Network Config and Setup

Additionally the server on which you run database server (like physical machine that is running somewhere or the cloud provider like AWS) the instances that we book there the network that you are using for hosting your Mongo Server should also be secure.

Backups and Software Updates

As an owner of the database environment you should regularly take backup of your data. The softwares that you are running should be up to date.

Let us talk about the below three in great detail :

  1. Authentication and Authorization
  2. Transport Encryption
  3. Encryption at Rest

Understanding the Role Based Access Control

Authentication and Authorization

Authentication is all about identification of the users in the database
Coming to Authorization,
Authorization is all about what these users may actually do in the database

MongoDB employs the Role Based Access Control System

Let us say we have the MongoDB server with three databases

  1. Admin database which is the special database that exists out of the box
  2. Blog database
  3. Shop database

Authentication can be enabled in a very easy way and suddenly MongoDBs server only allows access to the authenticated users.

Let us considered a user like some data analyst/software developer who directly connects with our shell or say we have the app code that uses the driver to connect to the database. The analyst or developer is NOT a user of your application, not the user
of the web application that you are building and we now need to login to the MongoDB Server. With our username and password, we can do that since authentication was enabled that means user needs to exist on the MongoDB server otherwise the login of the user will not be possible.

Now say we get loggedin but we have no rights to do anything…

The users in MongoDB are not just entities that are made up of username and passwords but they are also assigned some roles and these roles are basically the group of the privileges

A privilege is a combination of the resource and the action.

A resource would be something like the products collection in the Shop database and an action would be an insert() command for example to insert a product for example in our products collection

Actions are basically the task commands that we can do in our MongoDB database and resources define what resources we can access based on the access privileges that we are granted.

Typically multiple privileges are grouped into something called as the ROLES

That means a user has a role and that role includes all the privileges holding actions and resources that makes sense for this user.

This is the model that MongoDB uses since it is the most flexible model that Mongo has defined for its userbase. This allows us to create multiple owners where we can give every user exactly the rights that every user needs. We do not want to give every user all the rights because if we give all rights to any unauthorized person then they may do something malicious with our database which they were not designated to do.

Different types of database users

Admin – A real person who needs to be able to manage the database configuration and create users etc, create new databases, create new collections. The admin would need to be required to be work with data in the database. He does not need to be able to insert or fetch data.

Developer – A developer needs to be able to insert, delete, update or fetch data (all the CRUD operations that we discussed). The developer is not responsible for creating the users and manage the database configurations. This is not your job and the app code should not be able to do that.

Data Scientist – A data scientist needs to be able to fetch the data. He/she does not need to be able to create users, manage the database configuration or insert, edit, delete, update the data. His sole responsibility is to work with large amounts of data and derive valuable insights that are important for an organization. Working with large dataset along with strong analytic skills are a must for a data scientist.

CREATING A USER

Let us learn about creating and editing a user in MongoDB.

Users are created by a user with special permissions with the

createUser command. You then create the user with a username and the password. This user will have a couple of roles or atleast one role and each role will then contain a bunch of privileges. A user is created on the database. This does not limit the access of the user to that authentication database. But this is the database against which the user will have to authenticate. The exact rights the user has depends on the role that you have assigned to the user.

If we have the need we can also updateUser command, this means the admin can update the user that means for example we can use this to change the password

mongod --auth

Image description

We can also make use of the command

db.auth(“username goes here”,”password goes here”)

for signing up the user.

We can also connect by writing

mongo -u usernamesgoeshere -p passwordgoeshere

But what if we don’t have a user to begin with. MongoDB has a special solution which is called the localhost exception. More on this can be read here :

https://docs.mongodb.com/manual/core/localhost-exception

You are allowed to create one user who then can be allowed to create more users.

For this you need to switch to the admin database
and run the command

use admin

Then create a user

db.createUser({ user: "alex", pwd:"alex1234", roles: [ 
    "userAdminAnyDatabase"
]}) 

Built in Roles

MongoDB ships with a bunch of built in roles to cover most of the
use cases that you may require. You can also create your own roles
but that is pure admin task.

We got a typical role for the users of the database

Database user

read readWrite

You also got typical admin roles like the

dbAdmin

userAdmin

dbOwner

All database roles

readAnyDatabase

readWriteAnyDatabase

userAdminAnyDatabase

dbAdminAnyDatabase

Besides these roles we also have the cluster administration

Clusters are the concept where you have multiple MongoDB servers working together. So that you can have multiple machines running MongoDB servers and store your data which can then work and scale together. And managing this cluster of servers is ofcourse a meaningful task

clusterManager

clusterMonitor

hostManager

clusterAdmin

Backup/Restore roles

backup

restore

SuperUser Roles

dbOwner(admin)

userAdmin(admin)

userAdminAnyDatabase

root (the most powerful role)

root superuser can do everything

ASSIGNING ROLES TO USERS AND DATABASES

Run this command using the credentials of the created user

mongo --authenticationDatabase admin -u usernamegoeshere -p passwordgoeshere

db.createUser({
  user : 'appdev', 
  pwd : 'dev',
  roles : ['readWrite']
});

Successfully added user: { "user" : "appdev", "roles" : [ "readWrite" ] }

We can now authenticate in that user with the following command
db.auth('appdev','dev')

This gives 1. This 1 signal indicates that this works.

Adding SSL Transport Encryption

Transport Encryption

We have our application and this could be Node, Django, PHP
application that uses the MongoDB driver to communicate with
MongoDB Server to store the data and ofcourse it is important
that the data is encrypted whilst it is in transport so that
someone who is spoofing our connection can not read our data.
and MongoDB has everything for that built into it.

How we can secure our data whilst it is own its way from client to the server ?

To encrypt the data whilst it is in transport, MongoDB uses
SSL or actually TLS for encryption and uses public private key pair to decrypt this information on the server and to prove
to the server to prove that who we are. It is secure way of
encrypting our data and decrypting our data on the server.

While its own its way it is consistently updated.

ENCRYPTION AT REST

The data which is stored on our MongoDB Server in a file this
ofcourse might also be encrypted so that we can decrypt there
two different things

  1. The overall storage (feature built in for enterprise versions)
  2. The thing as a developer you can do is to encrypt certain values in your code. For example, if you are storing the user password you should hash that password and not store the plain text you can go so far for all data you always have a way for encrypting that.

So you can encrypt both your data as well as the overall file storage to achieve max security that is possible

Here are some of the important links that you must reference to know more about Security and Authentication in MongoDB:

Official “Encryption at Rest” Docs: https://docs.mongodb.com/manual/core/security-encryption-at-rest/

Official Security Checklist: https://docs.mongodb.com/manual/administration/security-checklist/

What is SSL/ TLS? => https://www.acunetix.com/blog/articles/tls-security-what-is-tls-ssl-part-1/

Official MongoDB SSL Setup Docs: https://docs.mongodb.com/manual/tutorial/configure-ssl/

Official MongoDB Users & Auth Docs: https://docs.mongodb.com/manual/core/authentication/

Official Built-in Roles Docs: https://docs.mongodb.com/manual/core/security-built-in-roles/

Official Custom Roles Docs: https://docs.mongodb.com/manual/core/security-user-defined-roles/

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Categories
backend javascript

Backend Developer Roadmap (2021)

Hey guys 👋🏻,
In this article, let us understand the roadmap that will help you in becoming a Backend Developer in 2021.

Every website that we build these days need a backend to manage the business logic of the application. To manage huge data for an application you need a database along with a API that makes the interaction between the client and the backend possible. Then there are other aspects to it that you need to care about when your application scales.

Image description

So without a further ado, let us first go over the technologies and skills that you need to succeed as a backend developer.

As a pre-requisite, you do need the knowledge of:

  1. Internet and How the Web Works
  2. Operating Systems
  3. Frontend Knowledge is a plus
  4. Some programming experience is also a plus though it can be learned along the way.

Needless to say if you want to succeed as a backend developer, you must have some programming knowledge under your belt. You do need to improve your coding skills if you are just getting started. For starters, getting familiar with the constructs of programming is important. A language like Java would be good to get you started with programming. You can also go for other languages like JavaScript, Ruby, Python etc.

Some of the prominent backend technologies are :

  1. Golang
  2. Node.js
Image description
  1. Ruby on Rails
Image description
  1. Django
Image description

and more…

Next comes the knowledge of version control system, also called as VCS. Now this enables developers to collaborate and work on a project along with that it also also allows us to manage the versions by recording the snapshots of the project history and even allow us to backtrack if a wrong change was committed. This way it limits the risk of errors and provides an efficient workflow to collaborate on projects.

For backend development, you can use the following version control systems.

Image description
  1. Git
  2. GitHub
  3. GitLab
  4. BitBucket

Database

Next you need the knowledge of a database :

Image description

A database as we know is an organized collection of data which can be structured or unstructured. The database caters to the storage aspect of our application. So it is responsible for storing the data of our application. We can also make queries against our database and retrieve the data in the form that we need.
Knowledge of databases is very important and a must have if you want to succeed as a backend developer.

Backend developers either use relational or NoSQL databases. Some of them are as follows:

Relational Databases

  1. PostgreSQL
  2. MySQL
  3. MS SQL
  4. Oracle
  5. MariaDB

NoSQL Databases

  1. MongoDB
  2. RethinkDB
  3. DynamoDB
  4. CouchDB
  5. ArangoDB
  6. Neo4J
    (to name a few)

Along with the knowledge of some of the databases described above, you will also need to be familiar with the basic database principles like :

ORMs, Transactions and Batches, ACID, Data Normalization, Indexing, Cursors etc.

APIs

Image description

APIs (Application Programming Interfaces) are a type of intermediate that allows services to communicate with one another. APIs are used by backend developers to connect different apps or services in order to give a better user experience on the frontend.

You should be aware of the following APIs:

  1. REST (important)

If you want to learn about REST APIs in detail, I do have an article on same :

  1. JSON
Image description
  1. SOAP
  2. GSON
  3. XML-RPC
  4. AES

Caching

Caching is the process of storing copies of files in a cache, or temporary storage location, so that they can be accessed more quickly. So essentially it is a technique for storing a copy of a resource in a cache (temporary storage location) so it can be accessed quickly without any delays (basically for fast access). The main goal of caching is to improve data retrieval performance while reducing the need to contact the slow-to-process underlying storage layer.

Here is a list of caching techniques and tools you should be aware of.

  1. CDN
  2. Server Side
  3. Client-Side
  4. Redis

Testing

Backend Testing is a testing method that checks the server side or database of web applications or a software. Backend testing is also known as Database Testing. The data entered in the front end will be stored in the back-end database. Backend developers utilize the following testing methods:

  1. Integration Testing
  2. Unit Testing
  3. Functional Testing

I may cover more on Testing in a separate article.

Code Analysis Tools

Code analysis is the analysis of source code that is performed without actually executing programs. It involves the detection of vulnerabilities and functional errors in deployed or soon-to-be deployed software.

Some of the tools used for code analysis are:

  1. SonarLint
  2. JUnit
  3. JaCoCo
  4. PMD
  5. SonarQube
  6. Qualys
  7. Jenkins

Architectural Patterns

An architectural pattern is a reusable solution to repeated issues in software development within a given context. The following are some of the most regularly used architectural patterns:

  1. Monolithic
  2. SOA
  3. Microservices
  4. CQRS
  5. Event Sourcing
  6. Serverless

Message Broker

A message broker is a part of software that allows systems, apps, and services to communicate with one another. A message broker is a module that converts the server’s formal messaging protocol into the client’s formal messaging protocol (receiver). Here is a list of some of the message brokers.

  1. RabbitMQ
  2. Kafka
  3. Kinesis
  4. JBOSS messaging

Containerization

Image description

Containerization is the packaging of software code with all required components, such as frameworks, libraries, and other dependencies, in order to create services that are isolated from one another in a container. Backend developers use containerization to make it easier to move or execute containers depending of their infrastructure or environment.

Docker is one of the most commonly used containers that you should learn.

Design Patterns

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. Design patterns are used to represent some of the best practices adapted by experienced object-oriented software developers. The following is a list of different design patterns that you should be familiar of.

  1. Singleton
  2. Factory
  3. Observer
  4. Decorator
  5. Adapter
  6. Mediator
  7. Composite
  8. Facade
  9. Iterator
  10. Proxy

WebHook

Webhooks are automated messages sent from apps when something happens. They have a message—or payload—and are sent to a unique URL—essentially the app’s phone number or address. Webhooks are almost always faster than polling, and require less work on your end.

They’re much like SMS notifications

A webhook, often known as a reverse API, is a method for an app to give real-time data to other apps. Webhooks, unlike APIs, do not require a request to be sent after a response. Instead, webhooks provide data as soon as it becomes available, without the need for a request or specific callbacks. The webhook’s fundamental characteristic makes it useful for both users and providers.

WebSocket

WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

The WebSocket API is a reducing technology that allows a two-way interactive communication session to be established between a user’s browser and a server. You can use this API to send messages to a server and obtain event-driven responses instead of asking the service. A WebSocket is a persistent link between a client and a server. It uses a TCP/IP socket connection to create a full-duplex, bi-directional communication channel over HTTP. Simply put, it’s a thin, lightweight layer over TCP that allows subprotocols to be used to lodge messages.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs web development

React.js – How to use Refs in React.js

Using refs in React.js

Hey guys 👋🏻,
In this article, let us cover the topic of How to use Refs in React.js

Let us investigate why React.js, a library that keeps your code away from DOM manipulation, keeps its doors open for you to access. React rethinks a view as a result of a state of a component. It provides JSX, a syntactic sugar over JavaScript, to design the view layer and then modifies the DOM itself rather than giving the control to the developer.

Still, the React team provided escape routes and kept the library open for certain situations that go beyond the scope of what React is designed for.

Creating Refs

Refs are escape routes and it’s better to avoid them whenever possible. When we obtain a DOM element using ref and then later modify its attribute, we might enter into a conflict with React’s diff and update approach.

Let’s start with a simple component and grab a DOM element using ref, assuming that you already know how to set up a basic react app.

In the above piece of code, we are using a react hook useRef to create and initialize a variable called buttonRef. We then assign buttonRef to ref attribute on button JSX element.

Using React refs

As we discussed earlier in this article we are declaring views based on the state, and though we are still altering the state using functions, we are not in direct control of the DOM changes. But in a few use cases, it makes sense to introduce refs in your code.

Focus Control

To better understand the problem statement let’s storify the situation.

Alex is a software development intern at Metflix Inc. and his manager has given him the task of creating contact forms. The manager has asked him to focus on the first input element in the form when a modal is opened. Alex is confused about how he can achieve this in React.js. Let’s help Alex out.

The first thing we need to do is to get a reference to the input.

Next, when our modal loads, we imperatively call focus on our input ref.

Note: You need to access the element through the current property of the ref you declare.

Detect if an element is contained

Similarly, we would want to take an action in the app when an event is dispatched. Like close the modal when the user clicks outside of it.

Here, we are checking if the user click is out of the modalRef limit. If it is we are calling close() function from props to close the modal.

Integrating DOM-based libraries

Like React, there are other utilities and libraries outside its ecosystem that have been in use for years. To use such libraries, refs come in handy.

GreenSock library is a popular choice for animation examples. To use it, we need to send a DOM element to any of its methods.

Let’s go back to our modal and add some animation

Forwarding Refs

Refs are useful for specific actions. The examples shown are a little simpler than what we usually find in a real-life web application. We need to deal with complex components and we barely use plain HTML elements directly. It’s common to use a ref from one component in another component.

The issue now is that passing a ref to this component will return its instance, a React component reference, and not the input element we want to focus on like in our first example.

React provides forwardRef, which allows you to define internally what element the ref will point at.

Now, when a parent component passes a ref value, it’s going to obtain the input, which is helpful to avoid exposing the internals and properties of a component and breaking its encapsulation.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript web development

Understanding Primitives and Reference Types in JavaScript

Hey guys 👋🏻,
In this article, let us cover the topic of Understanding Primitives and Reference Types in JavaScript.

Image description

Primitive value is stored directly in the location that the variable accesses. And the Reference values are objects that are stored in the heap. Reference value stored in the variable location is a pointer to a location in memory where the object is stored. This is something that I will demonstrate just a bit later. So stay with me.

Basic Primitive Types and Reference Types

JavaScript supports 5 primitive data types: number, string, Boolean, undefined, and null.

These types are referred to as primitive types because they are the basic building blocks from which more complex types can be built. Of these five, only number, string, and boolean are real data types in the sense of actually storing data.

Undefined and null are types that arise under special circumstances. The primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit.

Contrary to this, reference types can be of any length. They don’t have a fixed size.

For primitives, they are always copied as a whole value whereas for reference types they are copied by reference.

For variables that hold values we only compare their values whereas in case of reference types like objects, it is not the case.

Consider this example :

Image description
Image description

The above log gives true because both a and b are referencing to the exact same memory location. So let us say the memory for the arrow was allocated at some memory address of say 4k. So a is a reference that will point to the array object that is sitting at memory address 4k. So if you then assign a to b like we do above, then we have a new reference that points to the exact same object in the memory. So therefore since both the references point to the exact same object in the memory that is why it gives true for the strictly equality comparison between a and b (for the above log).

But if I declare another array with the exact same content say c.

and then do this :

Image description

Then the above log will resolve to false because this new array will get allocated at a different memory location say 5k. So if we compare a and c using a strict equality comparison, then it will resolve to false because both the references a and c point to different memory locations namely 4k and 5k respectively and hence you get false.

Now consider example for primitives. For this case you just compare the values. So if we have :

and then we say :

Then for the above log we make sure that both the type and the value are equal for the things (primitives under comparison). Both are 3 and both are numbers so hence we get true for this.

Next if we say

This will resolve to false because 3 and 4 are not equal.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
backend frontend javascript web development

What, Why and How to Validate ?

Hey guys 👋🏻,
In this article, let us learn about validation in case of application and learn about What, Why and How to Validate ?.

What, Why and How to Validate ?

To ensure that the data that you work with is the data in correct format, you need validation for it.

Let us answer these questiions :

Why should we use validation ?

Why would you add data validation to your application ?

When we have a user interacting with our website we typically have forms in any web application that we build. The bigger your application is the more data you will need from your users at some point of time. So we have that form which the user of the website interacts with and in the end this form is submitted with the POST request.

Then a request to the backend is sent along with the form data.
On our backend, we typically interact with the database using our server side logic or we may typically write our data into a file using the fs core module of Node.js. But in the end we take that data we receive and want to store it. This is why the need for data validation and sanitization arises.

If a user in our application would try to login with something that is not a valid email address, we should not allow access to the user, so we should prevent the user from entering something incorrect and getting access for that.

This is where we want validation to kick in.

How to validate and provide a good user experience ?

Obviously we got a user entering some data onto the form (Form Input) and let us say a Node.js application running on the server. We got a couple of places where we can validate, for example, we can validate on the client side of our application.

So right before any request hits the server, we can write some JavaScript, that for example checks the input at every keystroke and checks the input whilst the user is working on the form and then you can display an error right in the browser and this can greatly enhance the user experience on the client side for us.

This type of validation is totally optional because the user can see that code, user can change the validation and user can disable the JavaScript in the browser.

👉🏻This is not the protection that can secure you against incorrect data being sent to the server. This is not a secure solution it just is there to improve the user experience thing, so just to render proper error messages.

So,

we will focus on Server Side Validation. This is what we do with Node.js. This code can’t be used by the user, the user cannot disable this validation code that we define on the server side because this happens on the server not in the browser and this is the crucial part where we need to have validation to filter out incorrect values and this is what we will focus on. This ensures that we work with valid data in our node application and if we do plan on storing it ultimately we do store correct data in our database. There is also built in validation which we can use in databases like Mongo. This can be last resort. If we have strong validation on the server side no invalid data will be able to reach the database because you already filtered the incorrect data in the server side validation.

Validation at database level is also optional.

You must have to validate at server side at all means. If the validation fails, you must have to return an error message in user interface with helpful message and do not reload the page with the user input intact with the correct error message rendered in our user interface. This is because reloading offers a horrible experience to the end user and this would clear up all your form data and you would have to enter all the data again !

Example – Discussion on Validation for a Registration Page :

Some common validations for validating the form controls of a registration page are these :

✔ Check for the correctness of the mail. It is according to the format (must not be in bad format). It also must possess @ symbol
✔ Password must be atleast 6 characters long.
✔ Password and ConfirmPassword fields must match.

etc. etc.

Please note
You are not just restricted to above validations, you could have other validations as well for your form controls.

If you want to perform validation for your APIs that you have written using Express, you can make use of packages like

1. Express Validator

Image description

Though you could also make use of another npm package which is Joi for performing validation.
2. Joi

Image description

Now typically we want to validate for NON-GET requests because generally these are the cases in which the user will send some data to the server.

Sanitizing user input

We can ensure as an example that there is no extra whitespace in the string that is passed by the user on the left or on the right
You can normalize the email that is converted to lowercase or things like that. There is a couple of things that you can ensure that the data you get back is valid but is also stored in the uniform way without any extra whitespace or anything like that.
This is what we mean by Sanitization.

Sanitizing input is also that makes sense to be done. For sanitizing the email we can make use of the normalizeEmail method that is available on express-validator

Image description
Similarly, for sanitizing the password we can make use of the trim method that is also provided to us by the express-validator

Sanitizing data is important to ensure that your data is stored in the uniform format.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text