<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rahul Solanki</title>
    <description>The latest articles on DEV Community by Rahul Solanki (@rahulj9a).</description>
    <link>https://dev.to/rahulj9a</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F999735%2Fcbceb9de-8862-49ab-b4ee-a231395736a2.jpg</url>
      <title>DEV Community: Rahul Solanki</title>
      <link>https://dev.to/rahulj9a</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rahulj9a"/>
    <language>en</language>
    <item>
      <title>Step-by-Step Guide: Implementing NextAuth.js Authentication in Next.js 13 App Directory</title>
      <dc:creator>Rahul Solanki</dc:creator>
      <pubDate>Sun, 30 Jul 2023 15:40:10 +0000</pubDate>
      <link>https://dev.to/rahulj9a/a-guide-to-setting-up-authentication-with-nextauthjs-in-nextjs-13-app-directory-216i</link>
      <guid>https://dev.to/rahulj9a/a-guide-to-setting-up-authentication-with-nextauthjs-in-nextjs-13-app-directory-216i</guid>
      <description>&lt;p&gt;Hey everyone! In this article, we are going to set up Authentication for our web app with the help of Next-Auth With all of that will also show you to set up Prisma, react-query and other techs to ensure smooth and better authentication.&lt;/p&gt;

&lt;p&gt;The article will include:-&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Installation and folder structure&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Setting up Prisma and Environment variable&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Securing passwords with the help of bcrypt&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;API and hooks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Register, Login and check credentials&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Caching and fetching current Users with react-query&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Installation:-
&lt;/h2&gt;

&lt;p&gt;First of all, let's install all the dependencies-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; npm i next-auth


npm install -D prisma


npm install @prisma/client

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and now can install the rest of the dependencies later.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up prisma:-
&lt;/h2&gt;

&lt;p&gt;As we have already installed Prisma and Prisma client, now all we to initialize the Prisma in our project. To do so run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx prisma init

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After running this command you should see a file in your codebase something like this-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690726348871%2F4b3a238b-f20d-4d1d-af9a-c0396abd31bd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690726348871%2F4b3a238b-f20d-4d1d-af9a-c0396abd31bd.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690726510167%2Fd539a27f-571e-4980-8fce-1e61381c0e3c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690726510167%2Fd539a27f-571e-4980-8fce-1e61381c0e3c.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And this is the file where we have to set up our Prisma schema. next, you need to have your database URL; you can choose any database like MongoDB, MySQL or Postgresql. It's totally up to you. I am going to use Mysql for my project. After having your database URL, change the provider to the database you choose and paste the URL into the ".env" file in your root directory.&lt;/p&gt;

&lt;p&gt;(Note: Check if your ".env" file is included in ".gitignore" or not, if not then include it)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690726954006%2F18ddf42c-76d1-4011-947e-6588fe8164f0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690726954006%2F18ddf42c-76d1-4011-947e-6588fe8164f0.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After having all of this let's write our User model-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690727254151%2F95e0bd84-1598-499e-9ec1-3b60d82a1fe1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690727254151%2F95e0bd84-1598-499e-9ec1-3b60d82a1fe1.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can set up fields according to your application. Like I was building an e-commerce so I setup accordingly. To keep things unique like the id, username or email, you can use the 'unique' keyword. and to expect things in a specific type you can use 'String' or 'number' as I did in the case of String or id. In the case of id 'default(uuid())' will ensure to generate a random id everytime; Remember that there might be some changes in using 'default(uuid())'.&lt;/p&gt;

&lt;p&gt;and after setting up everthing all we have to do is to push the model into our database with the command-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx prisma db push

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now our Prisma model is setup, now we need to create a new library that can provide out Prisma client to global like this:-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690727886246%2F4e2b3614-1fa3-47e2-9f75-ca252560dbc6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690727886246%2F4e2b3614-1fa3-47e2-9f75-ca252560dbc6.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This library will ensure that next.js doesn't create a bunch of clients on every hot reload.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up Next-Auth:-
&lt;/h2&gt;

&lt;p&gt;Now let's set up our Next-auth, all we have to do is to create out next auth file with this file structure-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690728194985%2F46d1de64-2f3e-430e-ad3b-3e72accb0701.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690728194985%2F46d1de64-2f3e-430e-ad3b-3e72accb0701.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690728261126%2F4d0084aa-d9bc-4cc7-a59d-057e8465ffdf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690728261126%2F4d0084aa-d9bc-4cc7-a59d-057e8465ffdf.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now before setting up our 'authoptions' you need to install bcrypt&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install bcrypt
npm install -D @types/bcrypt

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and prisma adapter for our next auth&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @next-auth/prisma-adapter

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and in our config folder you can create a file named - 'nextauth.config.tsx'&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690728359421%2F9c2bf101-e1aa-4cfa-a5e1-a046a61b954e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690728359421%2F9c2bf101-e1aa-4cfa-a5e1-a046a61b954e.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;while signing-in we will pass the credentials, and the above code will check if we have the right credentials or not. The code will first accept the right form of credentials and then check if the credentials have email and password or not, and next it's going to check if the user's email exist in database or not and 'bcrypt.compare' function will check if the password is right or not.&lt;/p&gt;

&lt;p&gt;after creating the above file, create the variables-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690729009322%2F99aa2419-200d-4a2f-95e6-c0fcd4469b76.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690729009322%2F99aa2419-200d-4a2f-95e6-c0fcd4469b76.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and set the values whatever you want.&lt;/p&gt;

&lt;p&gt;Now let's build our register endpoint-&lt;/p&gt;

&lt;h2&gt;
  
  
  Register API endpoint-
&lt;/h2&gt;

&lt;p&gt;we will use bcrypt to hash our password. To know more about bcrypt you can read my another article on how to keep you user's password-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/godspowercuche/how-to-keep-users-password-safe-in-database-11pk-temp-slug-4439745"&gt;https://dev.to/rahulj9a/how-to-keep-users-password-safe-in-database-g0f&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690731912818%2F9cb9defd-398e-4ff7-89b5-df39f43269e4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690731912818%2F9cb9defd-398e-4ff7-89b5-df39f43269e4.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And this endpoint will create a new user in out database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get the user after signin-
&lt;/h2&gt;

&lt;p&gt;Now let's create a another lib. that will check if the user is sign in or not and if yes then will fetch the user's data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690729482215%2F71220c91-ca51-4954-a873-124dcb6d8ad5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690729482215%2F71220c91-ca51-4954-a873-124dcb6d8ad5.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The code will fetch the session details and extract the email to check if the user is registered or not and if yes then will fetch the user's data for further use.&lt;/p&gt;

&lt;p&gt;But to access the session we have to provide the session to the main layout file like this-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690730203187%2Fb41bf3de-3bbb-48d8-a90f-c021eb02b2eb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690730203187%2Fb41bf3de-3bbb-48d8-a90f-c021eb02b2eb.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//app&amp;gt;layout.tsx
import {ReactQueryProvider} from "@/providers/reactQueryProvider";
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    &amp;lt;html lang="en"&amp;gt;
      &amp;lt;body className={inter.className}&amp;gt;

          &amp;lt;NextAuthProvider&amp;gt;
            {children}
          &amp;lt;/NextAuthProvider&amp;gt;

      &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can't use this liberary directly and we need an API endpoint to fetch the current user's detail&lt;/p&gt;

&lt;h3&gt;
  
  
  API end point to fetch user's detail
&lt;/h3&gt;

&lt;p&gt;As we have fetch the user's data threw the serverAuth lib. all we have to do is build an api to facilitate our frontend.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690729867896%2Fe5184f15-c7a9-4081-8cd3-cd42f51e5f96.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690729867896%2Fe5184f15-c7a9-4081-8cd3-cd42f51e5f96.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we have build API to fetch currentUser's detail. But we don't want to make API calls again and again throughout the app. So lets's cache the User's detail using react-query&lt;/p&gt;

&lt;h3&gt;
  
  
  Caching our current User-
&lt;/h3&gt;

&lt;p&gt;install react-query&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i react-query

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and build a hook can be accessed throughout the app. So to do that we have to provide the query client to the main layout file and that can be done like this-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690730357837%2F2b379978-6e1b-44e9-884c-21a37236e5de.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690730357837%2F2b379978-6e1b-44e9-884c-21a37236e5de.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { NextAuthProvider } from "@/providers/nextAuthProvider";
import {ReactQueryProvider} from "@/providers/reactQueryProvider";
 export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    &amp;lt;html lang="en"&amp;gt;
      &amp;lt;body className={inter.className}&amp;gt;
        &amp;lt;ReactQueryProvider&amp;gt;
          &amp;lt;NextAuthProvider&amp;gt;
             {children}
          &amp;lt;/NextAuthProvider&amp;gt;
        &amp;lt;/ReactQueryProvider&amp;gt;
      &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and now the useCurrentUser hook-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690730498924%2F0314ac59-fb31-400f-beff-2603883e520b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1690730498924%2F0314ac59-fb31-400f-beff-2603883e520b.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The hook will cache the details of User and provide that to the frontend while keep checking if the user's details have changed or not and if it is changed then will fetch again in the background.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final result-
&lt;/h2&gt;

&lt;p&gt;Register Modal-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { signIn } from "next-auth/react";
import { useCallback, useState } from "react";
import Input from "../Input";
import Modal from "../Modal";
import axios from "axios";

const RegisterModal = () =&amp;gt; {
     const [email, setemail] = useState("");
     const [password, setpassword] = useState("");
     const [name, setname] = useState("");
     const [username, setuserName] = useState("");
     const [loading, setloading] = useState(false);

     const onSubmit = useCallback(async () =&amp;gt; {
          try {
               setloading(true);

               //add Register and login

               await axios.post("/api/register", {
                    email,
                    password,
                    username,
                    name,
               });

               signIn("credentials", { email, password });

          } catch (error) {
               console.log(error);

          } finally {
               setloading(false);
          }
     }, [email, password, username, name]);

     const bodyContent = (
          &amp;lt;div className="flex flex-col gap-4"&amp;gt;
               &amp;lt;Input
                    placeholder="Email"
                    onChange={(e) =&amp;gt; setemail(e.target.value)}
                    value={email}
                    disabled={loading}
               /&amp;gt;
               &amp;lt;Input
                    placeholder="Name"
                    onChange={(e) =&amp;gt; setname(e.target.value)}
                    value={name}
                    disabled={loading}
               /&amp;gt;
               &amp;lt;Input
                    placeholder="UserName"
                    onChange={(e) =&amp;gt; setuserName(e.target.value)}
                    value={username}
                    disabled={loading}
               /&amp;gt;
               &amp;lt;Input
                    placeholder="Password"
                    type="password"
                    onChange={(e) =&amp;gt; setpassword(e.target.value)}
                    value={password}
                    disabled={loading}
               /&amp;gt;
          &amp;lt;/div&amp;gt;
     );

     return (
          &amp;lt;div&amp;gt;
               &amp;lt;Modal
                    disabled={loading}

                    title="Create an account"
                    actionLabel="Regsiter"

                    onSubmit={onSubmit}
                    body={bodyContent}

               /&amp;gt;
          &amp;lt;/div&amp;gt;
     );
};

export default RegisterModal;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Login Modal-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import { useCallback, useState } from "react";
import Input from "../Input";
import Modal from "../Modal";

import { signIn } from "next-auth/react";

const LoginModal = () =&amp;gt; {

     const [email, setemail] = useState("");
     const [password, setpassword] = useState("");
     const [loading, setloading] = useState(false);

     const onSubmit = useCallback(async () =&amp;gt; {
          try {
               setloading(true);
               await signIn("credentials", {
                    email,
                    password,
               });

          } catch (error) {
               console.log(error);
          } finally {
               setloading(false);
          }
     }, [email, password]);

     const bodyContent = (
          &amp;lt;div className="flex flex-col gap-4"&amp;gt;
               &amp;lt;Input
                    placeholder="Email"
                    onChange={(e) =&amp;gt; setemail(e.target.value)}
                    value={email}
                    disabled={loading}
               /&amp;gt;
               &amp;lt;Input
                    placeholder="Password"
                    type="password"
                    onChange={(e) =&amp;gt; setpassword(e.target.value)}
                    value={password}
                    disabled={loading}
               /&amp;gt;
          &amp;lt;/div&amp;gt;
     );

     return (
          &amp;lt;div&amp;gt;
               &amp;lt;Modal
                    disabled={loading}

                    title="Login"
                    actionLabel="Sign in"

                    onSubmit={onSubmit}
                    body={bodyContent}

               /&amp;gt;
          &amp;lt;/div&amp;gt;
     );
};

export default LoginModal;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and whenever we need currentUser details-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import usecurrentUser from "@/hooks/useCurrentUser";
export default function User(){
const {data:currentUser,isLoading,isError} = usecurrentUser()
const email = currentUser.email
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and yes we have build our authentication. Ya! I know its a bit complicated and it will create pain just for 1 or 2 times as it's not that much hard of you try to understand what happening.&lt;/p&gt;

&lt;p&gt;Let me know your suggestion. I am also on &lt;a href="https://twitter.com/rahulj9a" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; where I used to post my journey and knowledge. So follow me there and DM for may help.&lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to build simple link preview without any external LIBRARY in react</title>
      <dc:creator>Rahul Solanki</dc:creator>
      <pubDate>Fri, 23 Jun 2023 15:55:20 +0000</pubDate>
      <link>https://dev.to/rahulj9a/how-to-build-simple-link-preview-without-any-library-in-js-2j84</link>
      <guid>https://dev.to/rahulj9a/how-to-build-simple-link-preview-without-any-library-in-js-2j84</guid>
      <description>&lt;p&gt;You must have encounter situation where you want to want to preview the link and for that you have to use external libraries. Now external libraries have their own advantages. But sometimes we just want our link preview component to be very simple and we don't want to fall into much complicated steps of using external libraries for example building our personal portfolio where we have to showcase our blogs that are published on different platforms. &lt;/p&gt;

&lt;h3&gt;
  
  
  Step1: Define preview componant
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function LinkPreview({ url }) {
  // State to hold the link preview data and loading status
  const [previewData, setPreviewData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() =&amp;gt; {
    // Fetches the link preview data when the URL prop changes
    const fetchData = async () =&amp;gt; {
      try {
        const response = await fetch(url);
        const data = await response.text();

        // Parsing logic to extract link preview data goes here

        setLoading(false);
      } catch (error) {
        console.error(error);
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  // Rendering logic for the link preview goes here

  return (
    // JSX code for rendering the link preview component
  );
}

export default LinkPreview;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;above code will take url as parameter and later process it.  The previewData state will hold the link preview data, and the loading state will track the loading status while fetching the data.Next, we use the useEffect hook to fetch the link preview data when the url prop changes. Inside the fetchData function, we use the fetch function to make a request to the provided URL. Once we have the response, we extract the necessary data, such as title, description, and image, from the HTML response which you have seen written in head section of HTML code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step2: Extracting Link Preview Data
&lt;/h3&gt;

&lt;p&gt;To extract the link preview data, we need to parse the HTML response and retrieve the relevant information. In this step, we will extract the title, description, and image using a basic parsing technique.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');
const title = doc.querySelector('title')?.textContent || '';
const description = doc.querySelector('meta[name="description"]')?.getAttribute('content') || '';
const image = doc.querySelector('meta[property="og:image"]')?.getAttribute('content') || '';

setPreviewData({ title, description, image });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will create a new instance of the DOMParser and parse the HTML data using 'parser.parseFromString(data, 'text/html')', where data is the HTML response. &lt;br&gt;
We will use 'doc.querySelector' to search for the required elements within the parsed HTML document. &lt;/p&gt;

&lt;p&gt;Finally, we will update the previewData state with the extracted information by calling 'setPreviewData({ title, description, image })'.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step3: Rendering the Link Preview
&lt;/h3&gt;

&lt;p&gt;Now that we have the link preview data available, let's update the rendering logic in the return statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
  &amp;lt;div&amp;gt;
    &amp;lt;h3&amp;gt;{previewData.title}&amp;lt;/h3&amp;gt;
    &amp;lt;p&amp;gt;{previewData.description}&amp;lt;/p&amp;gt;
    {previewData.image &amp;amp;&amp;amp; &amp;lt;img src={previewData.image} alt="Link Preview" /&amp;gt;}
  &amp;lt;/div&amp;gt;
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can style the componant according to your choice, I am not doing because i sucks at designing. and that's all for the very simple link preview component. &lt;/p&gt;

&lt;h3&gt;
  
  
  Final result-
&lt;/h3&gt;

&lt;p&gt;Now we can implement some error and loading state and with that we can also implement the redirect to website according to the link provided.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from 'react';

function LinkPreview({ url }) {
  const [previewData, setPreviewData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() =&amp;gt; {
    const fetchData = async () =&amp;gt; {
      try {
        const response = await fetch(url);
        const data = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(data, 'text/html');
        const title = doc.querySelector('title')?.textContent || '';
        const description = doc.querySelector('meta[name="description"]')?.getAttribute('content') || '';
        const image = doc.querySelector('meta[property="og:image"]')?.getAttribute('content') || '';

        setPreviewData({ title, description, image });
        setLoading(false);
      } catch (error) {
        console.error(error);
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  if (loading) {
    return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;
  }

  if (!previewData) {
    return &amp;lt;p&amp;gt;Failed to fetch link preview.&amp;lt;/p&amp;gt;;
  }

  const handleClick = () =&amp;gt; {
    window.open(url, '_blank');
  };

  return (
    &amp;lt;div onClick={handleClick} style={{ cursor: 'pointer' }}&amp;gt;
      &amp;lt;h3&amp;gt;{previewData.title}&amp;lt;/h3&amp;gt;
      &amp;lt;p&amp;gt;{previewData.description}&amp;lt;/p&amp;gt;
      {previewData.image &amp;amp;&amp;amp; &amp;lt;img src={previewData.image} alt="Link Preview" /&amp;gt;}
    &amp;lt;/div&amp;gt;
  );
}

export default LinkPreview;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But what if it has a youtube video. The above code definately will not show the desired result. That what can we do?&lt;br&gt;
well here is an escape:&lt;br&gt;
We can check if a url is related to youtube or not and then using some methods we can extract the thumbnail of video for image section in link preview.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from 'react';

function LinkPreview({ url }) {
  const [previewData, setPreviewData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() =&amp;gt; {
    const fetchData = async () =&amp;gt; {
      try {
        const response = await fetch(url);
        const data = await response.text();

        const isYouTubeVideo = isYouTubeURL(url);
        if (isYouTubeVideo) {
          const videoId = extractYouTubeVideoId(url);
          const videoThumbnail = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`;

          setPreviewData({
            videoId,
            videoThumbnail,
          });
          setLoading(false);
        } else {
          const parser = new DOMParser();
          const doc = parser.parseFromString(data, 'text/html');
          const title = doc.querySelector('title')?.textContent || '';
          const description = doc.querySelector('meta[name="description"]')?.getAttribute('content') || '';
          const image = doc.querySelector('meta[property="og:image"]')?.getAttribute('content') || '';

          setPreviewData({
            title,
            description,
            image,
          });
          setLoading(false);
        }
      } catch (error) {
        console.error(error);
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  const isYouTubeURL = (url) =&amp;gt; {
    return url.includes('youtube.com') || url.includes('youtu.be');
  };

  const extractYouTubeVideoId = (url) =&amp;gt; {
    const videoIdRegex = /(?:\/embed\/|\/watch\?v=|\/(?:embed\/|v\/|watch\?.*v=|youtu\.be\/|embed\/|v=))([^&amp;amp;?#]+)/;
    const match = url.match(videoIdRegex);
    return match ? match[1] : '';
  };

  if (loading) {
    return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;
  }

  if (!previewData) {
    return &amp;lt;p&amp;gt;Failed to fetch link preview.&amp;lt;/p&amp;gt;;
  }

  const handleClick = () =&amp;gt; {
    window.open(url, '_blank');
  };

  if (previewData.videoId) {
    return (
      &amp;lt;div onClick={handleClick} style={{ cursor: 'pointer' }}&amp;gt;
        &amp;lt;img src={previewData.videoThumbnail} alt="Video Thumbnail" /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }

  return (
    &amp;lt;div onClick={handleClick} style={{ cursor: 'pointer' }}&amp;gt;
      &amp;lt;h3&amp;gt;{previewData.title}&amp;lt;/h3&amp;gt;
      &amp;lt;p&amp;gt;{previewData.description}&amp;lt;/p&amp;gt;
      {previewData.image &amp;amp;&amp;amp; &amp;lt;img src={previewData.image} alt="Link Preview" /&amp;gt;}
    &amp;lt;/div&amp;gt;
  );
}

export default LinkPreview;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  'isYoutubeUrl' function
&lt;/h4&gt;

&lt;p&gt;It will check if youtube keyword is in there to sperate youtube link and normal link&lt;/p&gt;

&lt;h4&gt;
  
  
  'extractYouTubeVideoId' function-
&lt;/h4&gt;

&lt;p&gt;It will be reponsible for extracting video ID, &lt;br&gt;
The pattern &lt;br&gt;
&lt;code&gt;(?:\/embed\/|\/watch\?v=|\/(?:embed\/|v\/|watch\?.*v=|youtu\.be\/|embed\/|v=))([^&amp;amp;?#]+)&lt;/code&gt; &lt;br&gt;
is used to match various YouTube URL formats, including 'embed', 'watch?v=, v/', 'watch?...v=', and 'youtu.be/'. The captured group ([^&amp;amp;?#]+) captures the video ID.&lt;br&gt;
We then use the match method on the url string with the videoIdRegex to search for a match. If a match is found, the video ID is extracted using match[1]. If no match is found, the function returns an empty string.&lt;/p&gt;

&lt;p&gt;And after finding we will get the thumbnail image easily.&lt;/p&gt;

&lt;p&gt;and that's it.&lt;/p&gt;

&lt;p&gt;Follow me on twitter - &lt;a href="//twitter.com/rahulj9a"&gt;@Rahulj9a&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>programming</category>
    </item>
    <item>
      <title>Easiest way to Create React tables (NEXTJS)</title>
      <dc:creator>Rahul Solanki</dc:creator>
      <pubDate>Sat, 27 May 2023 14:15:29 +0000</pubDate>
      <link>https://dev.to/rahulj9a/easiest-way-to-create-react-tables-nextjs-2g18</link>
      <guid>https://dev.to/rahulj9a/easiest-way-to-create-react-tables-nextjs-2g18</guid>
      <description>&lt;p&gt;You must have encounter the situations where you have to build a react table, and honestly they are some real problem. So we can use some component library to make them easy, like we can use some component libraries like material UI but the problem with tables in material UI is that you have to ship a very large amount of javascript to browser as it should be a client side component. &lt;br&gt;
But now this problem is solved with a new component DATA TABLE by &lt;a href="https://ui.shadcn.com/" rel="noopener noreferrer"&gt;shadcn UI&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbo6o6xa64zdr7jg74lbm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbo6o6xa64zdr7jg74lbm.png" alt="Data table preview by shadcn UI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can filter and sort the email, can check all the fields, can enable and disable any sort of columns, and above all this have built-in pagination&lt;/p&gt;

&lt;p&gt;So let's build it&lt;br&gt;
first of all install the npm package by running command&lt;br&gt;
&lt;code&gt;npm install @tanstack/react-table&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
and here is the folder structure:&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Folder structure&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;app&lt;br&gt;
└── payments&lt;br&gt;
    ├── columns.tsx&lt;br&gt;
    ├── data-table.tsx&lt;br&gt;
    └── page.tsx&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The column component&lt;/strong&gt; is where we declare what data is shown for each column for example the email and amount  &lt;/p&gt;

&lt;p&gt;and to display all the information we will use the &lt;strong&gt;DataTable component&lt;/strong&gt; which will handle all the data&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;

&lt;p&gt;read the comments within the code:&lt;/p&gt;

&lt;h4&gt;
  
  
  Column.tsx:
&lt;/h4&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

"use client"

import { ColumnDef } from "@tanstack/react-table"

// This type is used to define the shape of our data. e.g we want our id to be string and status none other than these four options
export type Payment = { 
  id: string
  amount: number
  status: "pending" | "processing" | "success" | "failed"
  email: string
}

export const columns: ColumnDef&amp;lt;Payment&amp;gt;[] = [
//we can set normal fields like this
  {
    accessorKey: "status",
    header: "Status",
  },
  {
    accessorKey: "email",
    header: "Email",
  },
//
  {
    accessorKey: "amount",
    header: () =&amp;gt; &amp;lt;div className="text-right"&amp;gt;Amount&amp;lt;/div&amp;gt;,
    cell: ({ row }) =&amp;gt; {
      const amount = parseFloat(row.getValue("amount"))
      const formatted = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
      }).format(amount)

//we can format the amount in any currency without any use of external package

      return &amp;lt;div className="text-right font-medium"&amp;gt;{formatted}&amp;lt;/div&amp;gt;  
    },
  },
]



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  DataTable.tsx
&lt;/h4&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

"use client"
//we have to import a lot of things and here are they
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table"

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"

//now we are expecting 2 props: columns and the data(that we are expecting from the page component)
interface DataTableProps&amp;lt;TData, TValue&amp;gt; {
  columns: ColumnDef&amp;lt;TData, TValue&amp;gt;[]
  data: TData[]
}

export function DataTable&amp;lt;TData, TValue&amp;gt;({
  columns,
  data,
}: DataTableProps&amp;lt;TData, TValue&amp;gt;) {
// and now we will use this useReactTable hook
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel()

// and yes adding pagination can be done with just this above one line 

  })

  return (
    &amp;lt;div className="rounded-md border"&amp;gt;
      &amp;lt;Table&amp;gt;
        &amp;lt;TableHeader&amp;gt;
          {table.getHeaderGroups().map((headerGroup) =&amp;gt; (
            &amp;lt;TableRow key={headerGroup.id}&amp;gt;
              {headerGroup.headers.map((header) =&amp;gt; {
                return (
                  &amp;lt;TableHead key={header.id}&amp;gt;
                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                  &amp;lt;/TableHead&amp;gt;
                )
              })}
            &amp;lt;/TableRow&amp;gt;
          ))}
        &amp;lt;/TableHeader&amp;gt;
        &amp;lt;TableBody&amp;gt;
          {table.getRowModel().rows?.length ? (
            table.getRowModel().rows.map((row) =&amp;gt; (
              &amp;lt;TableRow
                key={row.id}
                data-state={row.getIsSelected() &amp;amp;&amp;amp; "selected"}
              &amp;gt;
                {row.getVisibleCells().map((cell) =&amp;gt; (
                  &amp;lt;TableCell key={cell.id}&amp;gt;
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  &amp;lt;/TableCell&amp;gt;
                ))}
              &amp;lt;/TableRow&amp;gt;
            ))
          ) : (
            &amp;lt;TableRow&amp;gt;
              &amp;lt;TableCell colSpan={columns.length} className="h-24 text-center"&amp;gt;
                No results.
              &amp;lt;/TableCell&amp;gt;
            &amp;lt;/TableRow&amp;gt;
          )}
        &amp;lt;/TableBody&amp;gt;
      &amp;lt;/Table&amp;gt;

//now to use the pagination we will use the buttons

&amp;lt;button onClick={()=&amp;gt;table.previouspage()}&amp;gt;Previous page&amp;lt;/button&amp;gt;
&amp;lt;button onClick={()=&amp;gt;table.nextpage()}&amp;gt;Next Page&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and here is out page.tsx folder:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import { Payment, columns } from "./columns"
import { DataTable } from "./data-table"

async function getData(): Promise&amp;lt;Payment[]&amp;gt; {
// and this Payment[] is imported from .columns which will again controll the type of that data that is passed from the server component to the client component

// Fetch data from your API here.

  return [
    {
      id: "728ed52f",
      amount: 100,
      status: "pending",
      email: "m@example.com",
    },
    // ...
  ]
}

export default async function DemoPage() {
  const data = await getData()

  return (
    &amp;lt;div className="container mx-auto py-10"&amp;gt;
      &amp;lt;DataTable columns={columns} data={data} /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and that's all, don't forget to check the &lt;a href="https://ui.shadcn.com/docs/components/data-table" rel="noopener noreferrer"&gt;official documentation&lt;/a&gt; of the component &lt;/p&gt;

&lt;p&gt;Follow me on &lt;a href="https://twitter.com/DEVOSORUS_J9A" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; and &lt;a href="https://www.instagram.com/devosorus/" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;&lt;br&gt;
for more such content &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;DEVOSORUS&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>react</category>
      <category>nextjs</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Accessibility in web development: designing for all users</title>
      <dc:creator>Rahul Solanki</dc:creator>
      <pubDate>Mon, 24 Apr 2023 06:49:41 +0000</pubDate>
      <link>https://dev.to/rahulj9a/accessibility-in-web-development-designing-for-all-users-1kj2</link>
      <guid>https://dev.to/rahulj9a/accessibility-in-web-development-designing-for-all-users-1kj2</guid>
      <description>&lt;p&gt;&lt;strong&gt;Web accessibility&lt;/strong&gt; a topic that is often underrated especially among beginners and sometimes even the experienced developers, but what is web accessibility. Web accessibility basically means designing and developing websites to ensure that all users, including those with disabilities,like dyslexia or color blindness, can access and use them. In this article, we will discuss the importance of accessibility in web development and provide some best practices for designing for all users.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Is Accessibility Important?
&lt;/h2&gt;

&lt;p&gt;Accessibility is essential because it ensures that all individuals, including those with disabilities, have equal access to information and technology. The internet has become a vital part of everyday life, and it is critical that everyone has access to it.&lt;/p&gt;

&lt;p&gt;Web accessibility ensures that individuals with disabilities can use and navigate websites and online content as effectively as individuals without disabilities. Inaccessible websites can prevent users from accessing essential information, completing tasks, and can even lead to legal issues.&lt;/p&gt;

&lt;p&gt;Moreover, accessibility is not just important for individuals with disabilities. It can also benefit users with temporary disabilities, such as a broken arm, users with slow internet connections, and even elderly users who may have difficulty with technology.&lt;/p&gt;

&lt;p&gt;In addition to the ethical and moral considerations of ensuring that all users have access to online content, there are also legal considerations. Many countries have laws and regulations that require websites to be accessible, and failure to comply can result in legal action and financial penalties.&lt;/p&gt;

&lt;p&gt;Overall, accessibility is crucial for creating a more inclusive online environment and ensuring that all individuals have access to information and technology. It is important for web developers to prioritize accessibility and create websites that are usable and accessible to all users. &lt;/p&gt;

&lt;h2&gt;
  
  
  Designing for Accessibility: Best Practices
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Use Semantic HTML
&lt;/h3&gt;

&lt;p&gt;Semantic HTML is the practice of using HTML elements that accurately describe the content they contain, rather than just using generic divs and spans. Semantic HTML improves the accessibility, SEO, and maintainability of a website.By using semantic HTML, screen readers and other assistive technologies can better understand the content and provide a more accessible experience for users.&lt;/p&gt;

&lt;p&gt;Here's an example of how semantic HTML can be used:&lt;/p&gt;

&lt;p&gt;Let's say you're creating a website that has a section for articles. In the past, you may have used a generic div to create the section, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="articles"&amp;gt;
  &amp;lt;div class="article"&amp;gt;
    &amp;lt;h2&amp;gt;Title&amp;lt;/h2&amp;gt;
    &amp;lt;p&amp;gt;Content&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;div class="article"&amp;gt;
    &amp;lt;h2&amp;gt;Title&amp;lt;/h2&amp;gt;
    &amp;lt;p&amp;gt;Content&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, this code doesn't provide any information about the content it contains, making it less accessible to users who rely on assistive technology, such as screen readers.&lt;/p&gt;

&lt;p&gt;Instead, using semantic HTML, you can use the section and article elements, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;section class="articles"&amp;gt;
  &amp;lt;article&amp;gt;
    &amp;lt;h2&amp;gt;Title&amp;lt;/h2&amp;gt;
    &amp;lt;p&amp;gt;Content&amp;lt;/p&amp;gt;
  &amp;lt;/article&amp;gt;
  &amp;lt;article&amp;gt;
    &amp;lt;h2&amp;gt;Title&amp;lt;/h2&amp;gt;
    &amp;lt;p&amp;gt;Content&amp;lt;/p&amp;gt;
  &amp;lt;/article&amp;gt;
&amp;lt;/section&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the section element describes the purpose of the content as a collection of articles, and each article element describes a single article. This provides more information about the content to assistive technology and makes it more accessible to users with disabilities.&lt;/p&gt;

&lt;p&gt;By using semantic HTML, you can provide more context and meaning to your website's content, making it more accessible, understandable, and maintainable.&lt;/p&gt;

&lt;h3&gt;
  
  
  Provide Alternative Text for Images
&lt;/h3&gt;

&lt;p&gt;Images are an essential component of many websites, but they can present barriers for users with visual impairments. Providing alternative text (alt text) for images allows screen readers to describe the image to the user.&lt;br&gt;
Here's an example of how alt text can be used:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;img src="example.jpg" alt="A smiling woman holding a dog on a leash"&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the img element includes the alt attribute, which provides a description of the image. The alt text, "A smiling woman holding a dog on a leash," describes the content of the image and provides context for users who are unable to see the image.&lt;br&gt;
It's also important to note that decorative images, such as background images or images that don't add any information to the content, should have empty alt text.&lt;/p&gt;

&lt;h3&gt;
  
  
  Ensure Color Contrast
&lt;/h3&gt;

&lt;p&gt;Color contrast is important for users with visual impairments who rely on high contrast to differentiate between text and background colors. Ensuring that text has a high contrast with its background can help users with low vision or color blindness.&lt;br&gt;
You can read this topic in more detail in the below article on mdn website:&lt;br&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast"&gt;https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Use Descriptive Link Text
&lt;/h3&gt;

&lt;p&gt;Links should be descriptive of their destination and should make sense out of context. For example, "Click Here" is not a descriptive link, but "Read More About Web Accessibility" is.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use ARIA (Accessible Rich Internet Applications) Attributes
&lt;/h3&gt;

&lt;p&gt;ARIA attributes are HTML attributes that provide additional information to assistive technologies about the purpose and function of UI elements. Using ARIA attributes can make web content more accessible for users with disabilities.&lt;br&gt;
You can read below article for more detail about this topic:&lt;br&gt;
&lt;a href="https://www.w3.org/WAI/standards-guidelines/aria/"&gt;https://www.w3.org/WAI/standards-guidelines/aria/&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Keyboard Accessibility
&lt;/h3&gt;

&lt;p&gt;Users with motor impairments or who use assistive technologies rely on keyboard navigation to navigate web content. Ensuring that all interactive elements are accessible via keyboard navigation is a crucial aspect of web accessibility.&lt;br&gt;
Here are some tips for improving keyboard accessibility on your website:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Make links and buttons keyboard accessible: Ensure that links and buttons can be accessed and activated using only the keyboard, by using the tabindex attribute and the Enter key to activate them.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Ensure focusability and visibility: Make sure that keyboard users can see where they are on the page by ensuring that all focusable elements, such as links, buttons, and form fields, are visually distinguishable from other page elements.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Provide clear and concise instructions: Provide clear and concise instructions for keyboard users on how to navigate and interact with the website. This can include instructions on how to use keyboard shortcuts or how to access hidden content.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion:
&lt;/h2&gt;

&lt;p&gt;Designing for accessibility means designing websites that are inclusive and accessible to all users. By implementing the best practices outlined above, web developers can create websites that are more accessible, usable, and enjoyable for all users, regardless of their abilities or disabilities. By prioritizing accessibility, web developers can create a more equitable online experience for everyone&lt;/p&gt;

&lt;p&gt;Now you are here don't forget to follow me &lt;a class="mentioned-user" href="https://dev.to/rahulj9a"&gt;@rahulj9a&lt;/a&gt; &lt;br&gt;
And on twitter with username &lt;a href="https://twitter.com/rahulj9a"&gt;rahulj9a&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Have a nice day  😊&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>frontend</category>
      <category>programming</category>
    </item>
    <item>
      <title>The Importance of Clean Code in JavaScript Development</title>
      <dc:creator>Rahul Solanki</dc:creator>
      <pubDate>Sat, 22 Apr 2023 14:59:45 +0000</pubDate>
      <link>https://dev.to/rahulj9a/the-importance-of-clean-code-in-javascript-development-4d8i</link>
      <guid>https://dev.to/rahulj9a/the-importance-of-clean-code-in-javascript-development-4d8i</guid>
      <description>&lt;p&gt;Enhance your JavaScript development skills with the best practices and techniques to write clean and robust code for optimal performance and maintain&lt;br&gt;
So in the past few years, Javascript has emerged as one of the most popular programming languages and its popularity is still increasing day by day. New features, libraries and frameworks are coming regularly and so the style of doing a task is also changing, making javascript a more powerful language that allows developers to build dynamic and interactive web applications. And while building these scalable and high-quality applications one has to write code in a way that can be maintainable, easy to understand for other developers, can easily be debugged and if it needs some change then can be modified very easily. So it is essential for a developer to write clean and maintainable code who wants to build a complex application. However, writing clean and maintainable JavaScript code can be quite challenging, especially for beginners. In this blog, we will discuss what clean code is, why it is essential, and how to write clean and maintainable JavaScript code that is also SEO-friendly.&lt;/p&gt;

&lt;p&gt;What is Clean Code?&lt;br&gt;
Clean code refers to code that is easy to read, understand, and modify. It follows best practices, is well-organized, and has a consistent style. Writing clean code is important because it makes it easier to collaborate with other developers, reduces the risk of errors, and makes it easier to maintain and extend the codebase over time. So, Clean code is characterized by the following traits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Clarity: The code should be easy to read and understand.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Simplicity: The code should be simple, without any unnecessary complexity.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Consistency: The code should follow a consistent style and use consistent naming conventions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Maintainability: The code should be easy to modify and maintain over time.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why is Clean Code Important?&lt;br&gt;
Generally beginners don't emphasize on writing clean code and just focus on the fact that code should work, and because beginners' projects are not usually that much complex and they don't have a team to collaborate with, writing clean code can be easily ignored, But as their project's size boom, it became a necessity to write it in a well-defined manner. So Clean code is important for several reasons:&lt;/p&gt;

&lt;p&gt;Readability: Clean code is easier to read and understand, which makes it easier for developers to collaborate and maintain the codebase over time. When code is hard to read, it can be difficult to understand what the code does or how it works, which can lead to errors and inefficiencies.&lt;/p&gt;

&lt;p&gt;Maintainability: Clean code is easier to maintain, which reduces the risk of bugs and makes it easier to add new features or make changes to the codebase. When code is poorly organized or inconsistent, it can be time-consuming and error-prone to modify or extend it.&lt;/p&gt;

&lt;p&gt;Scalability: Clean code is more scalable, which means it can handle growth and change more effectively. When code is clean, it is easier to add new functionality or refactor existing code without introducing bugs or compromising the overall quality of the codebase.&lt;/p&gt;

&lt;p&gt;Collaboration: Clean code is easier to collaborate on, which fosters a culture of teamwork and code ownership. When code is clean, it is easier for multiple developers to work on the same codebase without stepping on each other's toes or introducing conflicting changes.&lt;/p&gt;

&lt;p&gt;Efficiency: Clean code is more efficient, which means it uses fewer system resources and performs faster. When code is clean, it is easier to optimize and improve the codebase's performance without introducing bugs or other issues.&lt;/p&gt;

&lt;p&gt;Here is an example of a piece of code that is working fine but not in the category of clean code:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function a(b,c){let d=0;for(let e=0;e&amp;lt;b.length;e++){if(b[e]===c){d++}}return d}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code will run correctly but this code has several issues. First, the function name a is not descriptive or meaningful. Second, the function takes arguments b and c without any indication of what they represent. Third, the code uses a single-letter variable name d without any explanation of what it represents. Fourth, the for loop is hard to read and understand, with multiple levels of nesting and no spacing between elements. Finally, the code uses an if statement without braces, which can make it harder to read and understand.&lt;/p&gt;

&lt;p&gt;Here's an example of how this code could be refactored to be cleaner:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function countOccurrences(array, targetValue) {
  let count = 0;
  for (let i = 0; i &amp;lt; array.length; i++) {
    if (array[i] === targetValue) {
      count++;
    }
  }
  return count;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code is much cleaner and more readable. The function name countOccurrences is descriptive and meaningful, and the arguments array and targetValue indicate what the function expects as input. The variable name count is also more descriptive, and the for loop is easier to read and understand, with proper spacing and indentation. Finally, the if statement is enclosed in braces, making it easier to read and understand the logic of the function.&lt;/p&gt;

&lt;p&gt;Overall, clean code is important because it reduces the risk of errors, improves the efficiency and scalability of the codebase, fosters a culture of collaboration, and makes the codebase more maintainable and extensible over time.&lt;/p&gt;

&lt;p&gt;How to Write Clean and Maintainable JavaScript Code&lt;br&gt;
Now that we understand the importance of clean code let's discuss how to write clean and maintainable JavaScript code.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Use Meaningful and Consistent Naming Conventions
One of the most important aspects of writing clean code is using meaningful and consistent naming conventions. This includes naming variables, functions, and classes in a way that accurately reflects their purpose and meaning. It is also essential to use consistent naming conventions throughout the codebase so that other developers can easily understand what each variable represents.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
let a = 10;
let b = 20;

// Good Example:
let numberOfUsers = 10;
let totalRevenue = 20;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Comment Your Code
Adding comments to your code is also crucial for writing clean and maintainable JavaScript code. Comments help other developers understand your code by providing context and explaining how the code works. This is especially important for complex or challenging code sections, although the best code is self-explanatory and does not require comments, sometimes it's important when the codebase is huge and there is a lack of time, as comments can also help a developer to focus on the point where it needs to be rather than reading every single line of code&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
for (let i = 0; i &amp;lt; 10; i++) {
  if (i % 2 === 0) {
    console.log(i + ' is even');
  } else {
    console.log(i + ' is odd');
  }
}

// Good Example:
for (let i = 0; i &amp;lt; 10; i++) {
  // Check if i is even
  if (i % 2 === 0) {
    console.log(i + ' is even');
  } else {
    console.log(i + ' is odd');
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Use Modular Code
Using modular code is another critical element of writing clean and maintainable JavaScript code. This means breaking your code down into smaller, more manageable functions or independent modules that can be developed and tested separately. Modular code makes it easier to read and understand your code, as well as making it easier to modify, maintain and debug.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is an example:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
function calculateArea(width, height) {
  return width * height;
}

function calculatePerimeter(width, height) {
  return 2 * (width + height);
}

let width = 10;
let height = 20;

let area = calculateArea(width, height);
let perimeter = calculatePerimeter(width, height);

console.log('Area: ' + area);
console.log('Perimeter: ' + perimeter);

// Good Example:
function rectangle(width, height) {
  function calculateArea() {
    return width * height;
  }

  function calculatePerimeter() {
    return 2 * (width + height);
  }

  return {
    area: calculateArea,
    perimeter: calculatePerimeter
  };
}

let rect = rectangle(10, 20);

console.log('Area: ' + rect.area());
console.log('Perimeter: ' + rect.perimeter());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the poor example, the calculateArea() and calculatePerimeter() functions are defined separately, and the values for width and height are declared outside the functions. This makes the code harder to read and understand, and could lead to errors if the values for width and height were changed by mistake.&lt;/p&gt;

&lt;p&gt;In the good example, the rectangle() function encapsulates both the calculateArea() and calculatePerimeter() functions within a single module. The width and height values are passed as arguments to the rectangle() function, and are used internally by the calculateArea() and calculatePerimeter() functions. The rectangle() function returns an object with properties for area and perimeter, which can be called as functions to calculate the respective values. This approach makes the code more modular, easier to understand, and less error-prone.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Use Functional Programming Concepts
Functional programming concepts are another important aspect of writing clean and maintainable JavaScript code. This includes writing code that is stateless and immutable, which means that it does not change its state or properties externally. This results in code that is more predictable and testable, which can help you catch bugs before they become real problems. With that we can access a function later very easily and we don't have to write a piece of code again and again
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
if (user.age &amp;gt;= 18 &amp;amp;&amp;amp; user.age &amp;lt;= 65 &amp;amp;&amp;amp; user.hasValidLicense) {
  console.log('User is eligible to drive');
} else {
  console.log('User is not eligible to drive');
}

// Good Example:
function isEligibleToDrive(user) {
  return user.age &amp;gt;= 18 &amp;amp;&amp;amp; user.age &amp;lt;= 65 &amp;amp;&amp;amp; user.hasValidLicense;
}

if (isEligibleToDrive(user)) {
  console.log('User is eligible to drive');
} else {
  console.log('User is not eligible to drive');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the poor example, the condition for determining if a user is eligible to drive is written directly in the if statement. While it is functional, this code is not easily reusable and lacks readability. If we need to check whether a user is eligible to drive in another part of the application, we would have to rewrite the same condition again.&lt;/p&gt;

&lt;p&gt;In the good example, we've created a isEligibleToDrive() function that encapsulates the condition for checking eligibility. This function takes in the user object as a parameter and returns a boolean value based on whether the user meets the eligibility criteria. The if statement then calls this function, making the code much more readable and easier to understand.&lt;/p&gt;

&lt;p&gt;Moreover, this approach makes the code more modular, as we can easily reuse the isEligibleToDrive() function throughout our application. If the eligibility criteria change, we can simply update the isEligibleToDrive() function instead of searching for every instance where the condition is written directly in the code.&lt;/p&gt;

&lt;p&gt;By using modular code like this, we can improve the maintainability and scalability of our codebase.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Optimize for Performance
While performance is not the primary focus of writing clean and maintainable code, it is still an essential consideration. To improve your application's performance, you should minimize the use of global variables and use iteration loops instead of recursion. It is also a good idea to reduce the number of HTTP requests and optimize your code for memory usage.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's take a look at each of these performance considerations with an example of code:&lt;/p&gt;

&lt;p&gt;Minimizing the use of global variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
let username = 'John';

function greetUser() {
  console.log('Hello, ' + username + '!');
}

greetUser();

// Good Example:
function greetUser(username) {
  console.log('Hello, ' + username + '!');
}

let username = 'John';
greetUser(username);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the poor example, the username variable is declared in the global scope and is accessed within the greetUser() function. While this code is functional, it is not recommended because it can lead to naming conflicts and can make the code harder to maintain.&lt;/p&gt;

&lt;p&gt;In the good example, the username variable is passed as an argument to the greetUser() function instead of being accessed directly within the function. This approach minimizes the use of global variables and makes the code more modular and easier to maintain.&lt;/p&gt;

&lt;p&gt;Using iteration loops instead of recursion:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
function factorial(num) {
  if (num === 0) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
}

console.log(factorial(5)); // Output: 120

// Good Example:
function factorial(num) {
  let result = 1;
  for (let i = 1; i &amp;lt;= num; i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(5)); // Output: 120
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the poor example, the factorial() function uses recursion to calculate the factorial of a number. While this code is functional, it can cause performance issues for larger inputs, as each recursive call adds a new level to the call stack.&lt;/p&gt;

&lt;p&gt;In the good example, the factorial() function uses a for loop to calculate the factorial of a number. This approach is more efficient than recursion and can handle larger inputs without causing performance issues.&lt;/p&gt;

&lt;p&gt;Reducing the number of HTTP requests:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
function getDataFromAPI() {
  let data = null;
  $.ajax({
    url: '/api/data',
    success: function(response) {
      data = response;
    }
  });
  return data;
}

console.log(getDataFromAPI()); // Output: null
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Good Example:
function getDataFromAPI(callback) {
  $.ajax({
    url: '/api/data',
    success: function(response) {
      callback(response);
    }
  });
}

getDataFromAPI(function(data) {
  console.log(data); // Output: data from API
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the poor example, the getDataFromAPI() function makes an HTTP request to fetch data from an API and returns the data immediately. However, since the HTTP request is asynchronous, the getDataFromAPI() function returns null instead of the actual data.&lt;/p&gt;

&lt;p&gt;In the good example, the getDataFromAPI() function takes a callback function as an argument and calls this function with the actual data once the HTTP request is complete. This approach ensures that the actual data is returned only when it is available and minimizes the number of HTTP requests made by the application.&lt;/p&gt;

&lt;p&gt;Optimizing code for memory usage:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Poor Example:
let data = [];
for (let i = 0; i &amp;lt; 1000000; i++) {
  data.push(i);
}

console.log(data.length); // Output: 1000000

// Good Example:
function* generateData() {
  for (let i = 0; i &amp;lt; 1000000; i++) {
    yield i;
  }
}

let data = Array.from(generateData());

console.log(data.length);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Conclusion&lt;br&gt;
In conclusion, writing clean and maintainable JavaScript code is essential for any web developer. By using meaningful and consistent naming conventions, commenting on your code, using modular code, applying functional programming concepts, and optimizing for performance, you can write code that is easier to read, maintain, modify and debug. Writing clean code is not a one-time task but an ongoing effort. As you continue to develop your skills, strive to write cleaner, more maintainable code to become an expert in your field&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>HOW to Keep user's password safe in database</title>
      <dc:creator>Rahul Solanki</dc:creator>
      <pubDate>Thu, 19 Jan 2023 09:05:52 +0000</pubDate>
      <link>https://dev.to/rahulj9a/how-to-keep-users-password-safe-in-database-g0f</link>
      <guid>https://dev.to/rahulj9a/how-to-keep-users-password-safe-in-database-g0f</guid>
      <description>&lt;p&gt;If you have ever tried to build a backend where you have to build sign-in/sign-up, one of the main concerns is "how can I keep my user's password safe".&lt;br&gt;
Let's dive deep into it&lt;/p&gt;

&lt;p&gt;Let's say you have an authentication system and you have to store a username and password for your application in your database. Let's say the user's username is "Abc" and the password is "Abc$123" and you store it in plain words in your database. Now if any hacker/attacker tries to hack your database can steal all of your data about username and password and can easily access the user's account and can hack it. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hacker: I just hack the database now I can log in with &lt;br&gt;
  any user details.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But then what's the solution?&lt;br&gt;
Simply we will not store our password in plain word.&lt;/p&gt;

&lt;p&gt;Before learning how will we do that. let's see how our authentication will work&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Our client will enter a username and password&lt;/li&gt;
&lt;li&gt;After that our backend will check if the login 
credentials are right or wrong.&lt;/li&gt;
&lt;li&gt;Backend will talk with the database and will check if 
a user is already sign-up or not and then will return 
the respective results&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now let's get back to what can we do, we will do is we will make a hash of the user's password in our backend and then send that hashed value into our backend to store. while signup and checking while signing in. and this whole process is called password hashing.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hacker: Okay I will change that hashed value into a plain password&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Password hashing is basically a one-way function. It can convert a plain password into hashed value but can't convert a hashed value back into a plain password. Let's say your password is "abc$123" and after hashing value became "dfdfvsa#342123%EFW$". then there is no way we can change that hashed value into our actual password and if we try to log in with that hashed password it will generate another hash value according to the input.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjipzif2vnnki38yvs8po.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjipzif2vnnki38yvs8po.png" alt="map of storing password"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;now whenever we will try to log in the backend will again convert the password and will check if the converted value is stored or not. and now even if the hacker has stolen our user's login data only thing he will have is a converted value and he will not be able to login with that.&lt;br&gt;
How do that:&lt;br&gt;
we can use a npm package &lt;a href="https://www.npmjs.com/package/bcryptjs" rel="noopener noreferrer"&gt;bcryptjs&lt;/a&gt; to make a hash&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hacker: ha ha! I already have a table containing hash &lt;br&gt;
  values of millions of common passwords.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;now to avoid the situations where a hacker already have some converted hash values we use SALT. In salt, we add some random string of character in backend with user's password. So chances became very low that hacker have value of that hash value and that's how it can became very difficult for hacker to know the password. So let's say our salt is "12#42$6". So as user will enter his password salt will add to it in backend and then backend will convert it into hash.&lt;br&gt;
code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;salt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;bcrypt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;genSalt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 
&lt;span class="c1"&gt;//bcrypt can also generate salt for you&lt;/span&gt;
&lt;span class="nx"&gt;secPass&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;bcrypt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;password&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;salt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nx"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;User&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="na"&gt;password&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;secPass&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and our password will be remain secured in our database,&lt;/p&gt;

&lt;p&gt;additional info: There is also a concept called PEPPER which can be added to password to make it more secure&lt;br&gt;
For more info you can read &lt;a href="https://www.npmjs.com/package/bcryptjs" rel="noopener noreferrer"&gt;bcryptjs official documentation &lt;/a&gt; &lt;/p&gt;

&lt;p&gt;You can contact me on &lt;a href="https://twitter.com/rahulj9a" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;. &lt;br&gt;
Suggest me on what topics I should write on next?&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Copy vs Reference in Javascript</title>
      <dc:creator>Rahul Solanki</dc:creator>
      <pubDate>Wed, 11 Jan 2023 07:38:07 +0000</pubDate>
      <link>https://dev.to/rahulj9a/copy-vs-reference-in-javascript-2p1g</link>
      <guid>https://dev.to/rahulj9a/copy-vs-reference-in-javascript-2p1g</guid>
      <description>&lt;p&gt;Have you ever try to copy the value of an array and realized that new variable that you assigned is actually not a copy but a reference.&lt;br&gt;
Sometimes we are intended to copy the value of an array or an object and apply the same method that we do to copy a normal string or a number like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// will return 1 1&lt;/span&gt;
&lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// will return 1 2&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but if we try this it does not copy the value of array or object but instead create a reference and then whenever we try to change the value of second variable, the value of first one also changed like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;players&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Wes&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Rahul&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Sarah&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;team&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;players&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;players&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// ['Wes', 'Rahul', 'Sarah']&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;team&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// ['Wes', 'Rahul', 'Sarah']&lt;/span&gt;

&lt;span class="nx"&gt;team&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;raj&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;players&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// ['Wes', 'Rahul', 'raj']&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;team&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// ['Wes', 'Rahul', 'raj']&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in above code as we see, when we change the value of "team[2]", value of "players[2]" also changed. and same case is with objects, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Rahul&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;21&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;captain&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt;

&lt;span class="nx"&gt;captain&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// {name:"Rahul", age:"21", score:50}&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;captain&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="c1"&gt;// {name:"Rahul", age:"21", score:50}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;that is second variable become a reference of first one;&lt;/p&gt;

&lt;p&gt;But than how to copy them?&lt;/p&gt;

&lt;p&gt;Well here are some methods to do so:&lt;br&gt;
for arrays:          &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;using .slice()&lt;/li&gt;
&lt;li&gt;using .concat()&lt;/li&gt;
&lt;li&gt;using ES6 methods&lt;/li&gt;
&lt;li&gt;using Array.from()&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;for objects:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;using Object.assign()&lt;/li&gt;
&lt;li&gt;using JSON.parse(JSON.stringify())&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Implementation:&lt;/p&gt;

&lt;p&gt;1).&lt;br&gt;
For Arrays:&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhgjqw2yyr5knzcsd8yvc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhgjqw2yyr5knzcsd8yvc.png" alt="Implementation of how to copy an array" width="800" height="819"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;2.)&lt;br&gt;
For Objects:&lt;br&gt;
i) Using Object.assign():-&lt;br&gt;
It will take 3 parameters:- &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;an empty object in order to copy&lt;/li&gt;
&lt;li&gt;Object whom which we want copy&lt;/li&gt;
&lt;li&gt;(optional) If we want any property to insert.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F77nnw57jkd6ojvymfiui.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F77nnw57jkd6ojvymfiui.png" alt="Implementation of Object.assign() " width="800" height="438"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;ii) using JSON.parse( JSON.stringify() ) :-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpwweqgc5ncwmnnheut8l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpwweqgc5ncwmnnheut8l.png" alt="Implementation of JSON.parse( JSON.stringify())" width="800" height="514"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Follow/DM me on &lt;a href="https://twitter.com/rahulj9a" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; for any help/collab&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>programming</category>
      <category>help</category>
    </item>
  </channel>
</rss>
