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
frontend javascript reactjs

When to use the useRef hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useRef hook and understand how and when to use it.

What is the useRef hook ?

useRef hook is something that I briefly discussed in one of my articles where I described useRef hook as something equivalent to

Removing the state updating function from the useState, so basically just extracting the piece of state and take away the ability of state updation. This is something that will be equivalent to the useRef hook. I also discussed in that article that both the ref and state values persists across renders, so it is not the case that on every subsequent re-render they get set back to some default. So do make a note of the above points.

useRef is a React Hook which accepts a single argument as the initial default value and gives us something called as a ref. A ref is kind of an object that has a property called as current.

Let us see an example :

function SomeComponent() { 

    const usernameRef = React.useRef(''); 
    const handleSomething = () => { 
       console.log(usernameRef.currrent); 
       usernameRef.current = someOtherValue; 
    }
}

Now the things to note here is that usernameRef.current is used to access the value of the ref and if we want to update the ref value, then we can simply do so by setting usernameRef.current to a value of our choice.

To know more about refs, check my existing article on useRef hook. Here is the link for the same :

Image description

https://dev.to/thenerdydev/useref-hook-useref-vs-usestate-3i7k

In the above article, I have also taken some examples where I have demonstrated the usage of the useRef hook, we have discussed :

1. Ref Example – 1 (An Interval Timer)
2. Ref Example – 2 (Working with DOM using refs)
3. The third thing that we discussed in that article was :

useRef just like useState persists a value across renders but unlike useState it does not trigger a re-render of the component.

So in essence,

useRef = useState – state updating function

If you don’t know about the useState, no worries. You can learn about the same in this article :

https://dev.to/thenerdydev/react-hooks-demystifying-the-usestate-hook-in-under-10-minutes-examples-video-29ab

Let’s sum up what we learnt :

A ref is a plain JavaScript Object
{ current: <some_value> }

If you want to create a ref with the current value as null, then you can also make use of the createRef method,
React.createRef()

This gives us :
{ current: null }

Next, useRef(someInitialValue) also gives us a ref { current: someInitialValue }. The interesting thing about useRef is that it memoizes this ref so that it stays persistent across multiple renders of the component.

Another point to make a note of is that :

useRef(null) is basically equivalent to useState(React.createRef())[0]
But this kind of abuses the functionality.

Lastly, we learnt that useState causes a re-render in contrast to useRef. The state and the ref values (both) persist across re-renders.

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.

Categories
reactjs

Memoizing with React.useMemo

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useMemo hook and understand how and when to use it.

What is the useMemo hook ?

useMemo is a React Hook that was introduced to memoize expensive computations. Let us understand some basics about this. In order to understand the useMemo hook, let us understand its syntax:

const memoResult = useMemo(someFunction, dependencies);

So what happens with useMemo is that when the component renders for the first time, the useMemo hook invokes the someFunction (it could be any function, I am just calling it as someFunction) and memoizes the value that it computes for us and then it returns the result back to the component. Now the interesting thing here is that if during the subsequent renders, the list of dependencies that we specify do NOT change, then in that case useMemo will not invoke the someFunction but instead it will return the memoized value. Contrary to this, if the list of dependencies experience a change during subsequent renders, then useMemo will invoke the someFunction, memoize the result that it gets as a result of computation and then return it back to the component. So in essence, this is what happens in the useMemo hook.

Now let us see a simple example :

Let us say we have a component that deals with computation of factorial of a number, let’s call the component as FactorialResult. Now what this component does is that it computes the factorial of a number that is supplied into the input field by the user. Let us see the basic code for same :

import React from 'react' 
function computeFactorial(num) { 
   if(num == 0) { 
       return 1;
   }
   return num * computeFactorial(num - 1)
}
const FactorialResult = () => { 
  const [num, setNum] = React.useState(0); 
  const factorial = computeFactorial(num); 

  const handleChange = event => { 
         setNum(+event.target.value); 
  }
  return ( 
    <div>
      Factorial of 
      <input type="number" 
       value={num} 
       onChange={handleChange} />
      is {factorial}
    </div>

   );
}

Now every time, you change the input value, the factorial is re-calculated as a result of re-render.
Now how can we memoize this factorial calculation which itself is an expensive operation ? We want to memoize the factorial computation when the component re-renders. So for this we can make use of the useMemo hook. Let us make small changes in our code and memoize this factorial calculation. So here is the new code for the same component :

import React from 'react' 
function computeFactorial(num) { 
   if(num == 0) { 
       return 1;
   }
   return num * computeFactorial(num - 1)
}
const FactorialResult = () => { 
  const [num, setNum] = React.useState(0); 
  const factorial = React.useMemo(() => {
      computeFactorial(num)
   },[num]); 

  const handleChange = event => { 
         setNum(+event.target.value); 
  }
  return ( 
    <div>
      Factorial of 
      <input type="number" 
       value={num} 
       onChange={handleChange} />
      is {factorial}
    </div>

   );
}

Now every time you change the value of the num, the computeFactorial will get invoked but only if the num has changed. If num does not change on the re-render, then it will return the memoized result for its factorial and will not make that extra computeFactorial call. I hope that makes perfect sense.

Let’s see one more example to make the useMemo hook extremely clear.

Let us say we want to return the full name of a person, so for this let us say we have a function in some component that gives us the full name:

const fullName = React.useMemo(() => {
   return firstName + " " + lastName
},[firstName, lastName])

In above code, if the firstName or lastName change, then our fullName function will get re-invoked because we have specified firstName and lastName as dependencies. Please note : functions themselves usually don’t need to be re-computed, and their dependencies are mostly closure values that may change.

const fullName = React.useCallback(() => {
     return firstName + " " + lastName
}, [firstName, lastName]);

Now for above piece of code when firstName or lastName change, we don’t need a separate instance of the function on each re-render of the component, but we need exact the one and same instance of the function so that it has up to date values in the closure.

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

Categories
reactjs

🐱‍👤When to use the useCallback hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useCallback hook and understand how and when to use it.

What is the useCallback hook ?

useCallback is a React Hook which was introduced to prevent re-creation of a specific function in case our component re-renders.
It does so by memoizing the callback function that this hook takes and this memoized version will only change when one of the inputs has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

So typically we should make use of the useCallback hook in one of the following cases :

  1. If you are passing the function on to child component as props and the child component doesn’t often need re-rendering except when a certain prop change then useCallback might prevent certain re-renders.
  2. You are specifying a function as a dependency to useEffect. In such a case you must ensure that the function is not recreated on every render or the useEffect will be triggered on every render.

So in the essence, the decision to make use of the useCallback must be made judiciously instead of blindly since you might just overdo the advantage offered by useCallback and end up degrading the performance since useCallback will also memoize the functions and a frequently changing dependency might anyways need to recreate the function.

If the dependencies of the useCallback change, only then the function will get recreated otherwise it will use the exact one and the same instance of that function across the re-renders.

Example :

In JavaScript, we know that when a function gets executed we know that each and every thing (variables functions, objects etc) that is present within the function gets re-created into the memory. So this happens on each execution of the function. Now for a function we might not want it to get re-created on each re-render of the component and in turn we may want to use the exact same instance for that specific function in each of our renders. We might only want to re-create the function when a specific dependency which that function uses gets changed and NOT otherwise. This is something that we can achieve by making use of the useCallback hook.

Let’s see a simple Counter component.
Here we have a single piece of state which we call as counter and we have a corresponding state updating function for it which we named as setCounter. The initial value for counter is given as 0.
Next we have a handleIncrement counter function and all it does is that it increments the value of counter by 1.

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = () => {
    setCounter(counter + 1);
  }

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement}>Increment</button>
  </div>
}

Now the interesting thing to note here is that the handleIncrement function will get re-created on each render of the component. This means that each time the component re-renders, handleIncrement function will get re-created at a separate spot in memory. And due to this reason, when React tries to make a referential equality comparison, it finds a change because of the re-creation of the handleIncrement function.

Now what if we wrap this with the useCallback hook ?

What the useCallback does is that it internally caches the first created version of the function and returns it to the caller if the listed dependencies haven’t changed. In case the listed dependencies does change, then it automatically gives us a new instance of that function.
So if we introduce the useCallback hook into our above code, then our code should look something like this :

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = React.useCallback(() => {
    setCounter(counter + 1);
  }, [])

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement }>Increment</button>
  </div>
}

Now with the above code, what React will do is that it will cache the handleIncrement function internally and will make sure to return the exact same instance of the function in case no external dependencies of the useCallback have changed. In case, the external dependencies do change, then in that case a brand new instance of the handleIncrement function will get created for us. For our case, there are no external dependencies for the handleIncrement function.

Now caching the function internally by using the useCallback has its own cons. The cached instance of the function call will not have direct access to the variables of our current function call. Instead of that it will have visibility of the variables that were introduced in the initial closure call where the stored function was created. So in essence, this means that our call will not work for the updated variables. Therefore, we need to specify those variables or dependencies of the function that can change. The list of dependencies is to be passed as the second argument of the useCallback. In our example, we need to tell to useCallback function that we need a fresh version of our counter variable on each call. If we don’t do that, then the counter variable after the call will always be 1 and this is what comes from the original value 0 plus 1.

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = React.useCallback(() => {
    setCounter(counter + 1);
  }, [counter])

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement}>Increment</button>
  </div>
}

The above version of code will not re-render on every call.

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