Categories
backend database frontend javascript mongodb web development

New FULL Web Developer Course on YouTube

I decided to create a full Web Developer Course that will cover all the technologies that you need to kickstart your Full Stack Developer Journey. No bullshit, everything practical and relevant will be covered.

We will delve into following topics –

  1. HTML
  2. CSS
  3. JavaScript
  4. Node.js
  5. MongoDB

Check out the first video of this series where we cover the introduction to World Wide Web and the Evolution of the World Wide Web. The code for the video (if any) can be found on GitHub.

⭐ Check out the 10 JavaScript Projects in 2 Hours Video of my JavaScript Series where we build 12+ Projects using JavaScript :

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

Categories
backend javascript nodejs

How Authentication works in REST APIs ?

Hey everyone 👋🏻,

In this article, let us learn about more about REST APIs. This is the second article on the topic REST API. The first article on this topic can be read by clicking on the below link :

https://dev.to/thenerdydev/what-is-a-rest-api-288l

How authentication works in REST API ?

Alt Text

So we again have our client and server. The client in order to authenticate needs to first send the authentication data (credentials), so basically the email and the password. This password is then compared with the password that is kept in the database before granting the access to the user. Now if you are working with an Express based server, then you must have used a package called bcryptjs that helps with all of this stuff. In traditional applications, we used to check data on the server and if the data was valid and if it was valid, only then a session used to get established.

Why no sessions any more ?

Well, there is a reason for this. We do not use session any more because REST APIs are stateless. The client and the server do not share the same connection history which means that both are totally decoupled from each other. Here we don’t care about the clients. Every request is treated as standalone which means that every request should have all the data it needs to authenticate itself. With session, the server has to store the information about the client that it is authenticated and this is not how REST APIs work. Therefore this approach is not what we use nowadays.

Now here in this approach we will still check the validity of the email and password combination on the server. But contrary to what we do in case of sessions, here we return a token to the client and that token is something that gets generated on the server. This token would hold some information that can be validated by the server and this token will then be stored in the client so basically in the local storage of the browser. The client can then attach this token to every subsequent request it sents to the server. Stored token is sent to authorize subsequent request and targets the resource on the server which requires authentication.
That token can only be validated by the server who created that token.

Now what if you try to change or fake the token ?

If you try to change or fake the token on the client side, then that will be detected because the server uses a special algorithm to generate the token and you simply cannot fake it since the algorithm that uses to generate the private key is not known to you.

What’s that token ?

JSON data + Signature => => => JSON web token (JWT)

This JWT (json web token) is what gets returned to the client and the signature can only be verified by the server. So you cannot edit or tamper the token at the client because the server will detect and will invalidate the token. This is how authentication is done in REST APIs.
So in essence, we have a token which can be checked by the server but need not be stored by the server.

So generating the token is one thing, the server sends the token. Next we need to make sure that we can send the token back to the server/backend REST API and then we check for the existence and the validity of token before we allow the request to continue.

If no token is attached to the incoming request, we should simply block access to those routes which do require some form of proven authentication. Remember, it is for the private routes that you do need a token attached to the request so that the user can access them.

Now to basically append the token with request you could attach the token with query params of the url or you could send them inside the body of NON-GET requests. But the best solution would be to send the token along with the headers. The benefit of this is that this would keep your URL clean. Also headers makes a lot of sense for the meta information which our token is in the end.

Now with Express.js, we use the jsonwebtoken package for decoding and verifying our token on the backend.

We use jsonwebtoken.verify to both encode and verify the token on the backend. We can also use jsonwebtoken.decode at the server side as well but then it won’t verify the token there.

Wrap up

The REST API server doesn’t care about the client. Requests are handled in isolation which means that every request is treated as if it arrived for the first time. So here we don’t use sessions. The REST APIs does not store any sessions. They don’t store any client data.

Due to no involvement of sessions in REST APIs, authentication works a bit differently here. Each request needs to be able to send some data that proves the authenticity of that request. JSON Web Tokens are a common way of storing authentication information on the client and proving the authentication status.

JWTs are signed by the server and can only be validated by the server.

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 database mongodb

Running Geospatial Queries in MongoDB

Hey everyone 👋🏻,

In this article, let us learn about Running Geospatial Queries in MongoDB .

Geospatial Queries – Finding Places

Geospatial Queries are an interesting thing in MongoDB. You can fire queries not just for text, boolean, number, dates as condition but you can also create queries for locations like :

Find me all the restaurants within a radius of 2km.

Find me all the hospitals that near to this specific place

Image description

Running Geo Queries

Let us try to find all the places that are near my current location. So for this, let’s run this query. Make sure to use the latitude and longitude of your location before you fire the below query :

Image description

And here the $geoNear is the behind the scenes name of our $near query. For this we will need the geospatial index for this query to run.
Not all the geospatial queries require the index but they all will somehow benefit from having such an index.

To add such an index we can use the createIndex method on the
collection.

Image description

And if we repeat the same query, it should now succeed.

Image description

Now the question that must come in our mind is that how is near defined near, meaning that relative to what it is near. It does not make sense unless we restrict it.

We can also define $maxDistance which is a value present
in metres here. We can also define the $minDistance which is also a value define in metres

Let us now write a query to find all places that are near to us in a certain radius distance.

Find out all places that are near to us in a certain radius distance

Image description
This answers our first question regarding which points are near to our current location. Now this area could either be in form of a sphere, polygon etc., let us say we want to find out which points are inside of that area ?

This is another typical question that we often encounter and in order to answer this let us add more points to our database.
Let us add three more places :

Image description
Image description
Image description
Image description

Now let us run a query to find all the places that lie inside a certain area :

For finding such places, go to Google Maps :
Inside the Google Maps Section

  1. Go to Your Places tab.
  2. Create a new map there.
  3. Let us draw a polygon around our location.

$geoWithin will help us to find all the elements within a certain shape or certain object typically like a polygon.
$geoWithin takes a document as a value and here we can add a geometry object which is just the GeoJSON Object

Store all the four coordinates inside the points
p1, p2, p3, p4

Image description
Finding out if a user is inside a specific area. This can also be done using geospatial queries.

Let us see how we can find places within a certain area :

Image description

This is what we get as a result :

Image description

The $near method gives us the list of the places in the sorted order whereas the $geoWithin method will give us the list of the places in the unsorted order but we can sort them using the sort method on the records that we get back.

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 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
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