<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pawan Rijal on Medium]]></title>
        <description><![CDATA[Stories by Pawan Rijal on Medium]]></description>
        <link>https://medium.com/@pawanrijal?source=rss-ac132b921370------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yWUQU34P93ssvPpv</url>
            <title>Stories by Pawan Rijal on Medium</title>
            <link>https://medium.com/@pawanrijal?source=rss-ac132b921370------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:05:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pawanrijal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Step By Step Demo of Microservices with NestJS and RabbitMQ]]></title>
            <link>https://medium.com/@pawanrijal/step-by-step-demo-of-microservices-with-nestjs-and-rabbitmq-a9e91483bbf0?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e91483bbf0</guid>
            <category><![CDATA[architectural-design]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[step-by-step-guide]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 16:27:26 GMT</pubDate>
            <atom:updated>2025-01-16T16:27:26.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PB04W9tDAr19HbwrpxmHqQ.png" /></figure><p>Microservice architecture is known as the architectural style which organizes an application as a grouping of two or more services that are deployable independently and loosely coupled.</p><p><strong>Monolith vs Microservice architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*PSJRJtBQngbNFMwvNpSprw.png" /><figcaption>From amazon web services</figcaption></figure><p>In traditional monolith architecture there is only a single service which serves the client and has a single service. The processes are tightly coupled and if one process of an application experience high demand the entire architecture must be scaled resulting high complexity of the application.</p><p>If a single process fails with having tightly coupled architecture it impacts the whole application which add the risk of application availability.</p><p>But in microservice architecture there are different independent services which binds together as an application and is loosely coupled. The services communicate with each other using TCP(Transfer Control Protocol) or lightweight APIs. Each service of an application can be independently scaled, deployed.</p><p><strong>NestJS for building microservices</strong></p><p>Building microservices is a great use case for NestJS, a progressive Node.js framework that is notable for its adaptability and sturdy design.NestJS makes distributed systems easier to understand with its modular design, integrated support for microservice patterns, and smooth interface with message brokers like Redis, Kafka, RabbitMQ.</p><p>In addition to providing decorators and abstractions that facilitate communication between services, it makes use of TypeScript for type safety and maintainability. The scalability of Node.js and the best practices from frameworks like Angular are combined in NestJS to enable developers to design microservice architectures that are effective, scalable, and maintainable.</p><p><strong>Steps for implementing microservice architure in NestJS</strong></p><p><strong>I.</strong> Install NestJS CLI and Create Projects</p><pre>npm install -g @nestjs/cli<br>nest new user-service<br>nest new notification-service</pre><p><strong>II. </strong>Add Microservices Support</p><p>In both services, install the required package for RabbitMQ:</p><pre>npm install @nestjs/microservices amqplib<br>npm install amqp-connection-manager</pre><p><strong>III.</strong> User Service</p><p>In main.ts file of user-service configure the RabbitMQ microservice.</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { MicroserviceOptions, Transport } from &#39;@nestjs/microservices&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  app.connectMicroservice&lt;MicroserviceOptions&gt;({<br>    transport: Transport.RMQ,<br>    options: {<br>      urls: [&#39;amqp://localhost:5672&#39;],<br>      queue: &#39;user_queue&#39;,<br>      queueOptions: { durable: false },<br>    },<br>  });<br>  await app.startAllMicroservices();<br>  await app.listen(3001);<br>  console.log(&#39;User Service is running on port 3001&#39;);<br>}<br>bootstrap();</pre><p>In app.service.ts emit an event when user is created</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { ClientProxy, ClientProxyFactory, Transport } from &#39;@nestjs/microservices&#39;;<br><br>interface User {id:string,name:string}<br><br>@Injectable()<br>export class AppService {<br>  private client: ClientProxy;<br><br>  constructor() {<br>    this.client = ClientProxyFactory.create({<br>      transport: Transport.RMQ,<br>      options: {<br>        urls: [&#39;amqp://localhost:5672&#39;],<br>        queue: &#39;notification_queue&#39;,<br>        queueOptions: { durable: false },<br>      },<br>    });<br>  }<br><br>  createUser(user: User) {<br>    // Mocked the user creation logic<br>   console.log(`User created: ${JSON.stringify(user)}`);<br>    // Emit an event to the Notification Service<br>    this.client.emit(&#39;user_created&#39;, user);<br>  }<br>}</pre><p>In app.controller.ts handle the api request from client</p><pre>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br><br>@Controller()<br>export class AppController {<br>  constructor(private readonly appService: AppService) { }<br><br>  @Get(&#39;create-user&#39;)<br>  createUser() {<br>    this.appService.createUser({ id: &#39;1&#39;, name: &#39;Pawan Rijal&#39; });<br>    return &#39;User created&#39;;<br>  }<br>}</pre><p><strong>IV.</strong> Notification Service</p><p>In main.ts file of notification-service configure the RabbitMQ microservice just as in user-service.</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { MicroserviceOptions, Transport } from &#39;@nestjs/microservices&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  app.connectMicroservice&lt;MicroserviceOptions&gt;({<br>    transport: Transport.RMQ,<br>    options: {<br>      urls: [&#39;amqp://localhost:5672&#39;],<br>      queue: &#39;notification_queue&#39;,<br>      queueOptions: { durable: false },<br>    },<br>  });<br>  await app.startAllMicroservices();<br>  await app.listen(3002);<br>  console.log(&#39;Notification Service is running on port 3002&#39;);<br>}<br>bootstrap();</pre><p>In app.controller.ts listen for the user_created event and handle it.</p><pre>import { Controller } from &#39;@nestjs/common&#39;;<br>import { EventPattern } from &#39;@nestjs/microservices&#39;;<br><br>interface User { id: string; name: string }<br><br>@Controller()<br>export class AppController {<br><br>  @EventPattern(&#39;user_created&#39;)<br>  handleUserCreated(data: User) {<br>  //mock logic for sending notification<br>   console.log(`Notification sent for user: ${data.name}`);<br>  }<br>}</pre><p><strong>V. </strong>Run the services</p><p>Start RabbitMQ using docker.</p><pre>docker run -d --hostname my-rabbit --name rabbit -p 5672:5672 -p 15672:15672 rabbitmq:management</pre><p>Start user service.</p><pre>npm run start:dev</pre><p>Start notification service.</p><pre>npm run start:dev</pre><p><strong>VI.</strong> Testing Microservices</p><p>While testing use postman or other testing clients and hit the user-service api.</p><pre>GET http://localhost:3001/create-user</pre><p>I am just using GET request for this demo you can modify the business logic in your application.</p><p>Notification Service Output:</p><pre>Notification sent for user: Pawan Rijal</pre><p>In order to maintain system decoupling, this example shows how the User Service uses RabbitMQ to connect with the Notification Service. If you want to add more sophisticated features or explore further, let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e91483bbf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Authentication in a Next.js 14 App Using NextAuth and Prisma.]]></title>
            <link>https://medium.com/@pawanrijal/building-authentication-in-a-next-js-14-app-using-nextauth-and-prisma-59c9d67a0eca?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c9d67a0eca</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 16:08:43 GMT</pubDate>
            <atom:updated>2024-06-20T16:08:43.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*f6A78ItEfpXkV0Tu.png" /></figure><p>In this tutorial i am going to demonstrate how to add authentication in a NextJS App using Next Auth. I am going to use bun as runtime for running the NextJS app.</p><p><strong>Step I : Setup the Next 14 project</strong></p><pre>bunx create-next-app@latest next-auth-prisma</pre><p>You can enter the command above or follow the official <a href="https://nextjs.org/docs/getting-started/installation">documentation </a>of NextJS for setting up the project.</p><p><strong>Step II: Setup NextAuth api route</strong></p><p>After installation of next app then we need to install next-auth package in our app by following command.</p><pre>bun add next-auth</pre><p>Now we need to configure the auth options to be used in next auth so navigate to the base folder and create a new folder called <em>lib </em>and inside lib folder create a new file called <em>auth.ts </em>and copy the following code into it.</p><p><strong>/lib/auth.ts</strong></p><pre>import type { NextAuthOptions } from &quot;next-auth&quot;;<br>import CredentialsProvider from &quot;next-auth/providers/credentials&quot;;<br><br>export const authOptions: NextAuthOptions = {<br>  session: {<br>    strategy: &quot;jwt&quot;,<br>  },<br>  providers: [<br>    CredentialsProvider({<br>      name: &quot;Email and Password&quot;,<br>      credentials: {<br>        email: {<br>          label: &quot;Email&quot;,<br>          type: &quot;email&quot;,<br>          placeholder: &quot;example@example.com&quot;,<br>        },<br>        password: { label: &quot;Password&quot;, type: &quot;password&quot; },<br>      },t<br>      async authorize(credentials) {<br>        const user = { id: &quot;1&quot;, name: &quot;Admin&quot;, email: &quot;admin@admin.com&quot; };<br>        return user;<br>      },<br>    }),<br>  ],<br>};</pre><p>The above code demonstrates the process of setting up the next auth configuration. I have used CredentialsProvider from next auth you can use whichever provider you like like Google,Github,Facebook,etc for implementing these providers you can checkout the next auth official <a href="https://next-auth.js.org/providers/">docs </a>for configuration of these providers.</p><p>Now in credentials object there is email and password as fields which is displayed in login form and for the authorization step there is dummy credentials which return the mocked user object.</p><p>The next step is to create an API route which handles the authentication request from NextAuth. To get started create a new folder called <strong><em>api </em></strong>inside <strong><em>app </em></strong>directory and create a new folder <strong><em>auth</em></strong> inside <strong><em>api </em></strong>,create a new folder <strong>[…nextauth] </strong>which is a catch-all-routes folder inside <strong>auth </strong>and at last create a file name <strong>route.ts </strong>for api handling and paste the following code.</p><p><strong>/app/api/auth/[…nextauth]/route.ts</strong></p><pre>import { authOptions } from &quot;@/lib/auth&quot;;<br>import NextAuth from &quot;next-auth&quot;;<br><br>const handler = NextAuth(authOptions);<br>export { handler as GET, handler as POST };</pre><p>we have imported authOptions which we have previously configured inside NextAuth function and exported the next auth handler.</p><p><strong>Step III: Create Buttons</strong></p><p>To make navigating between pages in the application easier, we’ll create buttons instead of manually typing URLs in the browser. Create a new folder called <strong>components </strong>inside the base folder and create a file <strong>buttons.component.tsx</strong></p><p><strong>/components/buttons.component.tsx</strong></p><pre>&quot;use client&quot;;<br><br>import { signIn, signOut } from &quot;next-auth/react&quot;;<br>import Link from &quot;next/link&quot;;<br><br>export const LoginButton = () =&gt; {<br>  return (<br>    &lt;button style={{ marginRight: 10 }} onClick={() =&gt; signIn()}&gt;<br>      Sign in<br>    &lt;/button&gt;<br>  );<br>};<br><br>export const RegisterButton = () =&gt; {<br>  return (<br>    &lt;Link href=&quot;/register&quot; style={{ marginRight: 10 }}&gt;<br>      Register<br>    &lt;/Link&gt;<br>  );<br>};<br><br>export const LogoutButton = () =&gt; {<br>  return (<br>    &lt;button style={{ marginRight: 10 }} onClick={() =&gt; signOut()}&gt;<br>      Sign Out<br>    &lt;/button&gt;<br>  );<br>};<br><br>export const ProfileButton = () =&gt; {<br>  return &lt;Link href=&quot;/profile&quot;&gt;Profile&lt;/Link&gt;;<br>};</pre><p>Now import the buttons in home component</p><pre>import {<br>  LoginButton,<br>  LogoutButton,<br>  ProfileButton,<br>  RegisterButton,<br>} from &quot;@/components/buttons.component&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;main<br>      style={{<br>        display: &quot;flex&quot;,<br>        justifyContent: &quot;center&quot;,<br>        alignItems: &quot;center&quot;,<br>        height: &quot;70vh&quot;,<br>      }}<br>    &gt;<br>      &lt;div&gt;<br>        &lt;LoginButton /&gt;<br>        &lt;RegisterButton /&gt;<br>        &lt;LogoutButton /&gt;<br>        &lt;ProfileButton /&gt;<br>      &lt;/div&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Now we need to add JWT authentication in NextAuth so we need to define secret of JWT in <strong>.env </strong>file inside the root directory of the project.</p><p><strong>/.env</strong></p><pre>NEXTAUTH_SECRET=secret<br>NEXTAUTH_URL=http://localhost:3000</pre><p>Now visit <a href="http://localhost:3000/"><strong>http://localhost:3000/</strong></a><strong> </strong>to access the application and click the signin button on the homepage which redirects to the signin form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*-37yijMOMOuqwFT9QBe9Cg.png" /></figure><p>Since we have mock credentials we can use any email and password and submit the form and once it is successful it is redirected back to the home page. Now you can view the cookies of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvJXRhZuxUe4OupU4K_Zhg.png" /></figure><p><strong>Step IV: Integrating with database</strong></p><p>Now for real world users we need to integrate the database, I am going to use PostgreSQL as database and Prisma as ORM.</p><p>Create a new database and put the database url in <strong>.env</strong> file</p><pre>DATABASE_URL=postgresql://postgres:pawan123@localhost:5432/next-auth?schema=public</pre><p>Now install prisma ORM and bcryptjs for hashing the user password with the following command.</p><pre>bun add @prisma/client bcryptjs &amp;&amp; bun add -D ts-node prisma @types/bcryptjs</pre><p>To set up Prisma and connect to your Postgres database, run the following command to initialize Prisma in your project and create a datasource for PostgresSQL</p><pre>bun prisma init --datasource-provider postgresql</pre><p>Now create a User model inside the <strong>schema.prisma </strong>file.</p><pre>// This is your Prisma schema file,<br>// learn more about it in the docs: https://pris.ly/d/prisma-schema<br><br>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}<br><br>datasource db {<br>  provider = &quot;postgresql&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>model User {<br>  id       String @id @default(uuid())<br>  name     String<br>  email    String @unique<br>  password String<br>}</pre><p>Now u can create a register functionality to create a new user and store in database but i am going to seed an user directly to the database.To get started, create a <strong>seed.ts</strong> file in the <strong>prisma </strong>directory and copy the following code into it.</p><p><strong>prisma/seed.ts</strong></p><pre>import { PrismaClient } from &quot;@prisma/client&quot;;<br>import { hash } from &quot;bcryptjs&quot;;<br><br>const prisma = new PrismaClient();<br><br>async function main() {<br>  const password = await hash(&quot;password123&quot;, 12);<br>  const user = await prisma.user.upsert({<br>    where: { email: &quot;admin@admin.com&quot; },<br>    update: {},<br>    create: {<br>      email: &quot;admin@admin.com&quot;,<br>      name: &quot;Admin&quot;,<br>      password,<br>    },<br>  });<br>  console.log({ user });<br>}<br>main()<br>  .then(() =&gt; prisma.$disconnect())<br>  .catch(async (e) =&gt; {<br>    console.error(e);<br>    await prisma.$disconnect();<br>    process.exit(1);<br>  });</pre><p>To enable us to easily seed the database with a test user, we’ll add a script to the <strong>package.json </strong>file. Open the file and add the following script:</p><pre>{<br>&quot;prisma&quot;: {<br>    &quot;seed&quot;: &quot;ts-node --compiler-options {\&quot;module\&quot;:\&quot;CommonJS\&quot;} prisma/seed.ts&quot;<br>  },<br>}</pre><p>Now, generate migrations and push the user schema to the database with the following command</p><pre>bunx prisma migrate dev --name init</pre><p>After generating migrations use the following command to seed the user to database.</p><pre>npx prisma db seed</pre><p>Now, we’ll create a global <strong>PrismaClient</strong> instance using the @prisma/client package, which will enable us to communicate with the PostgreSQL database. To do this, we need to create a file named <strong>prisma.ts</strong> within the <strong>lib</strong> folder and add the following code to it.</p><pre>import { PrismaClient } from &quot;@prisma/client&quot;;<br><br>const globalForPrisma = global as unknown as { prisma: PrismaClient };<br><br>export const prisma =<br>  globalForPrisma.prisma ||<br>  new PrismaClient({<br>    log: [&quot;query&quot;],<br>  });<br><br>if (process.env.NODE_ENV !== &quot;production&quot;) globalForPrisma.prisma = prisma;</pre><p>After setting up prisma and database now we are going to authorize the signin form in <strong>auth.ts</strong></p><pre>import { prisma } from &quot;@/lib/prisma&quot;;<br>import { compare } from &quot;bcryptjs&quot;;<br>import type { NextAuthOptions } from &quot;next-auth&quot;;<br>import CredentialsProvider from &quot;next-auth/providers/credentials&quot;;<br><br>export const authOptions: NextAuthOptions = {<br>  session: {<br>    strategy: &quot;jwt&quot;,<br>  },<br>  providers: [<br>    CredentialsProvider({<br>      name: &quot;Sign in&quot;,<br>      credentials: {<br>        email: {<br>          label: &quot;Email&quot;,<br>          type: &quot;email&quot;,<br>          placeholder: &quot;example@example.com&quot;,<br>        },<br>        password: { label: &quot;Password&quot;, type: &quot;password&quot; },<br>      },<br>      async authorize(credentials) {<br>        if (!credentials?.email || !credentials.password) {<br>          return null;<br>        }<br><br>        const user = await prisma.user.findUnique({<br>          where: {<br>            email: credentials.email,<br>          },<br>        });<br><br>        if (!user || !(await compare(credentials.password, user.password))) {<br>          return null;<br>        }<br><br>        return {<br>          id: user.id,<br>          email: user.email,<br>          name: user.name,<br>          randomKey: &quot;Some random Key&quot;,<br>        };<br>      },<br>    }),<br>  ],<br>};</pre><p>Now to add custom keys, we can modify callbacks in the <strong>callbacks </strong>property of the NextAuth configuration. This way, you can include the information you need in the session object and JWT, and access it anytime and anywhere in your application.</p><pre>callbacks: {<br>    session: ({ session, token }) =&gt; {<br>      console.log(&quot;Session Callback&quot;, { session, token });<br>      return {<br>        ...session,<br>        user: {<br>          ...session.user,<br>          id: token.id,<br>          randomKey: token.randomKey,<br>        },<br>      };<br>    },<br>    jwt: ({ token, user }) =&gt; {<br>      console.log(&quot;JWT Callback&quot;, { token, user });<br>      if (user) {<br>        const u = user as unknown as any;<br>        return {<br>          ...token,<br>          id: u.id,<br>          randomKey: u.randomKey,<br>        };<br>      }<br>      return token;<br>    },<br>  },</pre><p><strong>Step V: Getting the NextAuth Session Data</strong></p><p>There are two ways of getting the authorized user session data inside next app.</p><p><strong>i. In server component</strong></p><p>we can use <strong>getServerSession </strong>function to get the session data inside the server components.</p><pre>import {<br>  LoginButton,<br>  LogoutButton,<br>  ProfileButton,<br>  RegisterButton,<br>} from &quot;@/components/buttons.component&quot;;<br>import { getServerSession } from &quot;next-auth&quot;;<br>import { authOptions } from &quot;@/lib/auth&quot;;<br><br>export default async function Home() {<br>  const session = await getServerSession(authOptions);<br>  console.log(session);<br><br>  return (<br>    &lt;main<br>      style={{<br>        display: &quot;flex&quot;,<br>        justifyContent: &quot;center&quot;,<br>        alignItems: &quot;center&quot;,<br>        height: &quot;70vh&quot;,<br>      }}<br>    &gt;<br>      &lt;div&gt;<br>        &lt;LoginButton /&gt;<br>        &lt;RegisterButton /&gt;<br>        &lt;LogoutButton /&gt;<br>        &lt;ProfileButton /&gt;<br><br>        &lt;h1&gt;Server Session&lt;/h1&gt;<br>        &lt;pre&gt;{JSON.stringify(session)}&lt;/pre&gt;<br>      &lt;/div&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Now for protecting the server pages from unauthorized users we can use following code which redirects to the signin page .</p><pre>if (!session) {<br>    redirect(&quot;/api/auth/signin&quot;);<br>  }</pre><p><strong>ii. In client component</strong></p><p>To retrieve session data in client component we need to use session provider provided by next auth and wrap the app in the session provider.</p><p>Create a folder <strong>providers </strong>in base directory and then create a new file <strong>NextAuthProvider.tsx </strong>and paste the following code.</p><pre>&quot;use client&quot;;<br><br>import { SessionProvider } from &quot;next-auth/react&quot;;<br><br>type Props = {<br>  children?: React.ReactNode;<br>};<br><br>export const NextAuthProvider = ({ children }: Props) =&gt; {<br>  return &lt;SessionProvider&gt;{children}&lt;/SessionProvider&gt;;<br>};</pre><p>Now wrap the provider in the <strong>layout.tsx </strong>file.</p><pre>import { NextAuthProvider } from &quot;./providers/NextAuthProvider&quot;;<br><br>export const metadata = {<br>  title: &quot;Create Next App&quot;,<br>  description: &quot;Generated by create next app&quot;,<br>};<br><br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;NextAuthProvider&gt;{children}&lt;/NextAuthProvider&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Now create a client component to get the session data.</p><pre>&quot;use client&quot;;<br><br>import { useSession } from &quot;next-auth/react&quot;;<br><br>export const User = () =&gt; {<br>  const { data: session } = useSession();<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Client Session&lt;/h1&gt;<br>      &lt;pre&gt;{JSON.stringify(session)}&lt;/pre&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>Now for protecting the client components from unauthorized users paste the following code in the client component.</p><pre>const { status } = useSession({<br>    required: true,<br>    onUnauthenticated() {<br>      redirect(&quot;/api/auth/signin&quot;);<br>    },<br>  });<br><br>  if (status === &quot;loading&quot;) {<br>    return &lt;p&gt;Loading....&lt;/p&gt;;<br>  }</pre><p><strong>Conclusion</strong></p><p>In this tutorial we have learned how to integrate NextAuth into the new Next.js 14 app. I hope you found this article informative and enjoyable. If you have any feedback or questions, please feel free to leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c9d67a0eca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a CRUD Application with Nest.js and TypeORM]]></title>
            <link>https://medium.com/@pawanrijal/building-a-crud-application-with-nest-js-and-typeorm-352a02c46234?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/352a02c46234</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 10:12:02 GMT</pubDate>
            <atom:updated>2024-01-07T10:15:30.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="nest js logo" src="https://cdn-images-1.medium.com/max/1024/1*ou2IZVfclXplqfd6nx6Wlw.jpeg" /></figure><p>Nest is a progressive Node JS framework for building efficient,scalable and reliable server-side applications (<a href="https://nestjs.com/">website</a>). Decorators are mostly used in this framework like Spring Boot framework of Java.</p><p>In this guide, we’ll walk through the process of setting up a Nest.js project, defining a data model with TypeORM, and implementing the basic CRUD operations (Create, Read, Update, Delete). By the end of this tutorial, you’ll have a solid understanding of how to build a scalable and maintainable backend application.</p><h3><strong>Prerequisites</strong></h3><p>Before we begin, make sure you have Node.js and npm installed on your machine. You can install the Nest CLI globally by running the following command:</p><pre>npm install -g @nestjs/cli</pre><h3>Step 1: Setting Up the Project</h3><p>Let’s start by creating a new Nest.js project. Open your terminal and run the following commands:</p><pre>nest new nest-crud-tutorial</pre><pre>cd nest-crud-tutorial</pre><pre>npm install @nestjs/typeorm typeorm</pre><p>We are going to use PostgreSQL as database so we need to install the respective package.</p><pre>npm install pg</pre><h3>Step 2: Configuring the database</h3><p>Create .env file at the root project directory and configure according to your database.</p><pre>POSTGRES_HOST=127.0.0.1<br>POSTGRES_PORT=5432<br>POSTGRES_USER=postgres<br>POSTGRES_PASSWORD=pawan123<br>POSTGRES_DATABASE=nest-crud<br>PORT=3000<br>MODE=DEV<br>RUN_MIGRATIONS=true</pre><p>Now in the default generated file app.module.ts configure TypeORM</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot({<br>      type: &#39;postgres&#39;,<br>      host: process.env.POSTGRES_HOST,<br>      port: parseInt(process.env.POSTGRES_PORT),<br>      password: process.env.POSTGRES_PASSWORD,<br>      username: process.env.POSTGRES_USER,<br>      entities: [],<br>      database: process.env.POSTGRES_DATABASE,<br>      synchronize: false,<br>      logging: true,<br>    }),<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><h3>Step 3: Creating Resource For User</h3><p>we are going to use the nest-cli for generating the dtos,entity,controller and service by the following command</p><pre>nest g resource user</pre><p>This command generate the necessary files to create a resource which has CRUD functionality.</p><h3>Step 4: Creating Entity</h3><p>Now, let’s define our data model by creating an entity using TypeORM. In this example, we’ll create a simple User entity with fullName and email properties.</p><pre>import {<br>  Entity,<br>  PrimaryGeneratedColumn,<br>  Column,<br>} from &#39;typeorm&#39;;<br><br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  fullName: string;<br><br>  @Column({ unique: true })<br>  email: string;<br>}</pre><p>Add the code to the generated user.entity.ts file.</p><h3>Step 5: Add Validation</h3><p>For validation nest provides a validation pipe as default for error handling. We can use validation pipe in main.ts file</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { ValidationPipe } from &#39;@nestjs/common&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  app.useGlobalPipes(<br>    new ValidationPipe({ whitelist: true }),<br>  );<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p>We need to install class-validator package for validation. Install using the following command</p><pre>npm install class-validator</pre><p>Now create dto in create-user-dto.ts file which define the data schema of the user.</p><pre>import {<br>  IsEmail,<br>  IsNotEmpty,<br>  IsString,<br>} from &#39;class-validator&#39;;<br><br>// create-user-dto<br>export class CreateUserDto {<br>  @IsNotEmpty()<br>  @IsString()<br>  fullName: string;<br><br>  @IsNotEmpty()<br>  @IsEmail()<br>  email: string;<br>}</pre><p>Also create update-user-dto.ts file which is a partial type of CreateUserDto and can have null values.</p><pre>import { PartialType } from &#39;@nestjs/mapped-types&#39;;<br>import { CreateUserDto } from &#39;./create-user.dto&#39;;<br><br>export class UpdateUserDto extends PartialType(CreateUserDto) {}</pre><h3>Step 6: Creating Service</h3><p>Next, create a service that interacts with the database using TypeORM. In the User Service we need to initialize a repository which is created from entity using dependency injection by TypeORM. Service layer handles the business logic in the application</p><pre>import {<br>  HttpException,<br>  Injectable,<br>} from &#39;@nestjs/common&#39;;<br>import { CreateUserDto } from &#39;./dto/create-user.dto&#39;;<br>import { UpdateUserDto } from &#39;./dto/update-user.dto&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { UserEntity } from &#39;./entities/user.entity&#39;;<br><br>@Injectable()<br>export class UserService {<br>  constructor(<br>    @InjectRepository(UserEntity)<br>    private readonly userRepository: Repository&lt;UserEntity&gt;,<br>  ) {}<br><br>  async create(<br>    createUserDto: CreateUserDto,<br>  ): Promise&lt;UserEntity&gt; {<br>    const userData =<br>      await this.userRepository.create(<br>        createUserDto,<br>      );<br>    return this.userRepository.save(userData);<br>  }<br><br>  async findAll(): Promise&lt;UserEntity[]&gt; {<br>    return await this.userRepository.find();<br>  }<br><br>  async findOne(id: number): Promise&lt;UserEntity&gt; {<br>    const userData =<br>      await this.userRepository.findOneBy({ id });<br>    if (!userData) {<br>      throw new HttpException(<br>        &#39;User Not Found&#39;,<br>        404,<br>      );<br>    }<br>    return userData;<br>  }<br><br>  async update(<br>    id: number,<br>    updateUserDto: UpdateUserDto,<br>  ): Promise&lt;UserEntity&gt; {<br>    const existingUser = await this.findOne(id);<br>    const userData = this.userRepository.merge(<br>      existingUser,<br>      updateUserDto,<br>    );<br>    return await this.userRepository.save(<br>      userData,<br>    );<br>  }<br><br>  async remove(id: number): Promise&lt;UserEntity&gt; {<br>    const existingUser = await this.findOne(id);<br>    return await this.userRepository.remove(<br>      existingUser,<br>    );<br>  }<br>}</pre><h3>Step 7: Creating Controller</h3><p>Build a controller to handle HTTP requests and interact with the service.</p><pre>import {<br>  Controller,<br>  Get,<br>  Post,<br>  Body,<br>  Patch,<br>  Param,<br>  Delete,<br>} from &#39;@nestjs/common&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br>import { CreateUserDto } from &#39;./dto/create-user.dto&#39;;<br>import { UpdateUserDto } from &#39;./dto/update-user.dto&#39;;<br><br>@Controller(&#39;users&#39;) //route group<br>export class UserController {<br>  constructor(<br>    private readonly userService: UserService,<br>  ) {}<br><br>  @Post()<br>  async create(<br>    @Body() createUserDto: CreateUserDto,<br>  ) {<br>    try {<br>      await this.userService.create(<br>        createUserDto,<br>      );<br><br>      return {<br>        success: true,<br>        message: &#39;User Created Successfully&#39;,<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        message: error.message,<br>      };<br>    }<br>  }<br><br>  @Get()<br>  async findAll() {<br>    try {<br>      const data =<br>        await this.userService.findAll();<br>      return {<br>        success: true,<br>        data,<br>        message: &#39;User Fetched Successfully&#39;,<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        message: error.message,<br>      };<br>    }<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  async findOne(@Param(&#39;id&#39;) id: string) {<br>    try {<br>      const data = await this.userService.findOne(<br>        +id,<br>      );<br>      return {<br>        success: true,<br>        data,<br>        message: &#39;User Fetched Successfully&#39;,<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        message: error.message,<br>      };<br>    }<br>  }<br><br>  @Patch(&#39;:id&#39;)<br>  async update(<br>    @Param(&#39;id&#39;) id: string,<br>    @Body() updateUserDto: UpdateUserDto,<br>  ) {<br>    try {<br>      await this.userService.update(<br>        +id,<br>        updateUserDto,<br>      );<br>      return {<br>        success: true,<br>        message: &#39;User Updated Successfully&#39;,<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        message: error.message,<br>      };<br>    }<br>  }<br><br>  @Delete(&#39;:id&#39;)<br>  async remove(@Param(&#39;id&#39;) id: string) {<br>    try {<br>      await this.userService.remove(+id);<br>      return {<br>        success: true,<br>        message: &#39;User Deleted Successfully&#39;,<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        message: error.message,<br>      };<br>    }<br>  }<br>}</pre><h3>Step 8: Wiring Everything Together</h3><p>Now, let’s connect the service, controller, and entity. Nest.js uses dependency injection to manage the application’s components. Make sure to import and register your services and controllers in user.module.ts file.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br>import { UserController } from &#39;./user.controller&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { UserEntity } from &#39;./entities/user.entity&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([UserEntity]),<br>  ],<br>  controllers: [UserController],<br>  providers: [UserService],<br>})<br>export class UserModule {}</pre><p>Congratulations! You’ve successfully created a basic CRUD application with Nest.js and TypeORM. We covered setting up the project, defining a data model, implementing services and controllers, and testing your application. This is just the beginning — Nest.js and TypeORM offer a wide range of features for building robust backend applications.</p><p>For your convenience, you can find the complete source code for this tutorial on my <a href="https://github.com/pawanrijal/nest-crud.git">GitHub repository</a>. Feel free to clone the repository and experiment with the code on your own.</p><p>Thank you for following along with our Nest.js and TypeORM CRUD tutorial. We hope you found it helpful on your journey to becoming a proficient backend developer. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=352a02c46234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Notifications in Laravel: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@pawanrijal/how-to-create-notifications-in-laravel-a-step-by-step-guide-19daa6b2fede?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/19daa6b2fede</guid>
            <category><![CDATA[laravel-notification]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-tutorials]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 07:20:00 GMT</pubDate>
            <atom:updated>2024-01-06T07:24:24.275Z</atom:updated>
            <content:encoded><![CDATA[<p>In the modern web applications, notifications can play the vital role in enhancing user experience about your application. Notifications are used to notify the user about the events in your application and to increase the engagement in desktop, web and mobile applications.</p><p>To achieve the functionality of notification Laravel provides a robust notification system that makes it easy to implement the notification in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBVqZRgkKgYCODCQVk0ARg.jpeg" /></figure><p><strong>Section I : Setting Up Laravel Project</strong></p><p><strong>Step 1: Install Laravel</strong></p><pre>composer create-project --prefer-dist laravel/laravel your-project-name</pre><p><strong>Step 2: Configure Database:</strong></p><p>Set up your database connection in the .env file.</p><p><strong>Step 3: Generate Authentication System (Optional):</strong></p><p>If your application doesn’t have user authentication yet, you may want to generate it using Laravel’s built-in scaffolding.</p><pre>php artisan make:auth</pre><p><strong>Section II : Creating notifications table</strong></p><p><strong>Step 4: Create a migration</strong></p><p>Generate a new migration file using the Artisan command:</p><pre>php artisan make:migration create_notifications_table</pre><p><strong>Step 5: Define the Notification Table Schema</strong></p><p>Open the generated migration file (located in the database/migrations directory). Define the schema for the notifications table within the up method:</p><pre>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>class CreateNotificationsTable extends Migration<br>{<br>    public function up()<br>    {<br>        Schema::create(&#39;notifications&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;unsignedBigInteger(&#39;user_id&#39;);<br>            $table-&gt;string(&#39;type&#39;);<br>            $table-&gt;morphs(&#39;notifiable&#39;);<br>            $table-&gt;text(&#39;data&#39;);<br>            $table-&gt;timestamp(&#39;read_at&#39;)-&gt;nullable();<br>            $table-&gt;timestamps();<br>            <br>            $table-&gt;index([&#39;user_id&#39;, &#39;read_at&#39;]);<br>        });<br>    }<br><br>    public function down()<br>    {<br>        Schema::dropIfExists(&#39;notifications&#39;);<br>    }<br>}</pre><p><strong>Step 6: Run the migration</strong></p><p>Execute the migration to create the notifications table in the database:</p><pre>php artisan migrate</pre><p><strong>Step 7: Configure the User Model</strong></p><p>Ensure that your User model (App\Models\User by default) uses the Illuminate\Notifications\Notifiable trait. This trait provides methods to retrieve and send notifications.</p><pre>use Illuminate\Notifications\Notifiable;<br><br>class User extends Authenticatable<br>{<br>    use Notifiable;<br>    <br>    // ...<br>}</pre><p><strong>Section III: Creating Notifications</strong></p><p><strong>Step 8: Create Notification Class</strong></p><p>Generate a new notification class using the Artisan command:</p><pre>php artisan make:notification NewNotification</pre><p>This will create a new notification class in the App\Notifications directory.</p><p><strong>Step 9: Customize the Notification</strong></p><p>Open the NewNotification.php file generated by Laravel. Customize the notification content by updating the toMail method to specify the message content that will be sent via email. Additionally, use the toDatabase method to customize the message content that will be stored in the notifications table.</p><pre>use Illuminate\Notifications\Notification;<br>use Illuminate\Notifications\Messages\MailMessage;<br><br>class NewNotification extends Notification<br>{<br>    public function toMail($notifiable)<br>    {<br>        return (new MailMessage)<br>            -&gt;line(&#39;The introduction to the notification for email.&#39;)<br>            -&gt;action(&#39;Notification Action&#39;, url(https://medium.com/&#39;/&#39;))<br>            -&gt;line(&#39;Thank you for using our application!&#39;);<br>    }<br><br>    public function toDatabase($notifiable)<br>    {<br>        return [<br>            &#39;message&#39; =&gt; &#39;The introduction to the notification for database.&#39;,<br>            // Add any additional data you want to store in the database<br>        ];<br>    }<br>}</pre><p><strong>Section IV: Triggering Notification</strong></p><p><strong>Step 10: Trigger Notification</strong></p><p><strong>10.1 Trigger Notification from Controller</strong></p><p>You can trigger the notification from your controller. For example, in a controller method:</p><pre>use App\Notifications\NewNotification;<br><br>public function sendNotification()<br>{<br>    $user = auth()-&gt;user();<br>    $user-&gt;notify(new NewNotification());<br>}</pre><p><strong>10.2 Trigger Notification from Event</strong></p><p>If you prefer using events, you can trigger notifications from events. Create an event:</p><pre>php artisan make:event SomethingHappened</pre><p>In the event listener (SomethingHappenedListener.php), handle the event and send the notification:</p><pre>public function handle(SomethingHappened $event)<br>{<br>    $user = $event-&gt;user; // Customize based on your event data<br>    $user-&gt;notify(new NewNotification());<br>}</pre><p><strong>Step 11: Display Notifications in the UI</strong></p><p>In your Blade view, you can display notifications which are saved by the database channel.</p><pre>@if (session(&#39;status&#39;))<br>    &lt;div class=&quot;alert alert-success&quot;&gt;<br>        {{ session(&#39;status&#39;) }}<br>    &lt;/div&gt;<br>@endif<br><br>@foreach(auth()-&gt;user()-&gt;notifications as $notification)<br>    {{ $notification-&gt;data[&#39;message&#39;] }}<br>@endforeach</pre><p>Finally, this blog has helped you create nottifications in Laravel, a useful feature that improves user interaction and communication in your online applications. First, we configured the database, set up a Laravel project, and optionally created an authentication mechanism. With an emphasis on the Database and Mail notification channels, we investigated the construction of notification classes.</p><p>You studied how to use the toMail and toDatabase methods to customise the content of notifications for email and the database, respectively. You may make sure that users receive critical changes via email and that the database stores them for future use by selecting several notification channels.</p><p>Notifying one or more people, displaying notifications in the system, and triggering notifications from controllers and events.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19daa6b2fede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“An Ember in the Ashes” book series by Sabaa Tahir review]]></title>
            <link>https://medium.com/@pawanrijal/ember-in-the-ashes-book-series-by-sabaa-tahir-review-687c76332536?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/687c76332536</guid>
            <category><![CDATA[books]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[fantasy]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[an-ember-in-the-ashes]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 11:48:43 GMT</pubDate>
            <atom:updated>2022-12-25T13:18:58.910Z</atom:updated>
            <content:encoded><![CDATA[<p>As I recently finished this book series, I loved the book series. This book is very well written and I was rooting for both characters from the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*ukRySUKNkKp4O5Z9Iw2gzA.jpeg" /></figure><p>This series world is based on the roman civilization and has very good world-building and different varieties of characters. The series follows two main characters, Laia and Elias who are fighting against the empire in their ways.</p><p>Laia is a scholar and a slave who is desperately trying to save her brother from the empire. She infiltrates the empire’s military academy known as Blackcliff Academy, to gather information about her brother’s whereabouts. In that academy, she meets Elias, a student at the academy who is torn between his duty to the empire and his moral code.</p><p>As Laia and Elias navigate the dangerous cutthroat world of the academy, they are drawn together in a forbidden romance. Meanwhile, a rebellion is brewing in the empire.</p><p>This series is a compelling and emotional tale of love, loyalty, and the quest for freedom. The characters are well-developed and the world-building is very immersive and detailed. The series is full of twists and turns, and the stakes are high as Laia and Elias fight against the empire.</p><p>This series consists of four books.</p><blockquote>An Ember in the Ashes</blockquote><blockquote>A Torch Against the Night</blockquote><blockquote>Reaper at the Gates</blockquote><blockquote>A Sky Beyond the Storm</blockquote><p>The series is well-written and will keep you on the edge of your seat from beginning to end. It is full of intense action and fast-paced plot twists that keep the reader engaged. It moves at a quick pace, and the plot is full of surprises and twists that keep the reader guessing.</p><p>Sabaa Tahir did a great job which captivates the writing style that draws the reader in and keeps them engaged throughout the series.</p><blockquote>The main theme of this book series are power, justice, and the cost of freedom, and encourages readers to think about these topics.</blockquote><p>Overall, I highly recommend the “Ember in the Ashes” series to fans of fantasy, action, and young readers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=687c76332536" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat GPT: The Future of Conversation?]]></title>
            <link>https://medium.com/@pawanrijal/chat-gpt-the-future-of-conversation-9441e60f4702?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/9441e60f4702</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 11:22:31 GMT</pubDate>
            <atom:updated>2022-12-19T11:22:31.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="chat-gtp" src="https://cdn-images-1.medium.com/max/1024/1*Vncy5xd41gUgJk0hVm2Nwg.jpeg" /></figure><p>In recent years, chatbots and virtual assistants have become increasingly prevalent in our daily lives, providing us with information, answering our questions, and even offering customer service. But what if these chatbots could do more than just provide pre-written responses? What if they could hold meaningful conversations with us, just like a human would?</p><p>Enter Chat GPT.</p><p>Chat GPT (short for Chat Generative Pre-trained Transformer) is a new type of chatbot that uses advanced natural language processing techniques to generate responses to user input in real-time. Based on the popular GPT-3 language model developed by OpenAI, Chat GPT is able to understand and respond to a wide range of topics and contexts, making it a potentially powerful tool for a variety of applications.</p><p>One of the key benefits of Chat GPT is its ability to generate responses that are more human-like and less robotic than traditional chatbots. By using pre-trained language models, Chat GPT can understand and respond to a wide range of topics, making it more versatile and capable of handling a greater range of conversation scenarios.</p><p>However, it’s important to note that Chat GPT is not a replacement for human interaction. While it may be able to hold meaningful conversations, it is still a machine and cannot replicate the full range of human emotions and responses.</p><p>So, is Chat GPT the future of conversation? Only time will tell, but it’s certainly an exciting development in the field of chatbots and virtual assistants, and has the potential to revolutionize the way we interact with technology.</p><p><strong>PS: This content is also generated by Chat GPT.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9441e60f4702" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement OTP (One-Time Password) verification in a Laravel application.]]></title>
            <link>https://medium.com/@pawanrijal/implement-otp-one-time-password-verification-in-a-laravel-application-541acf320fd3?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/541acf320fd3</guid>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 08:11:19 GMT</pubDate>
            <atom:updated>2022-12-19T08:11:19.363Z</atom:updated>
            <content:encoded><![CDATA[<p>To implement OTP (One-Time Password) verification in laravel application you can follow these steps:</p><p>Step I:Install the Laravel OTP package using Composer</p><pre>composer require laravel-otp</pre><p>Step II: Add the OTP service provider to the providers array in your config/app.php configuration file:</p><pre>&#39;providers&#39; =&gt; [<br>    // Other service providers...<br><br>    Mckenziearts\LaravelOTP\LaravelOTPServiceProvider::class,<br>],</pre><p>Step III: Publish the package’s configuration file by running this command:</p><pre>php artisan vendor:publish --provider=&quot;Mckenziearts\LaravelOTP\LaravelOTPServiceProvider&quot;</pre><p>Step IV: Update the .env file with your SMS gateway credentials. There are various SMS gateways available, such as Twilio, Nexmo, etc. Each SMS gateway has its own set of credentials that you will need to provide.</p><p>Step V: In your controller, use the sendOTP function to send the OTP to the user&#39;s phone number. For example:</p><pre>use Mckenziearts\LaravelOTP\Facades\OTP;<br><br>public function sendOTP(Request $request)<br>{<br>    $phone = $request-&gt;input(&#39;phone&#39;);<br>    $otp = OTP::send($phone);<br><br>    // Store the OTP in the session for later verification<br>    session([&#39;otp_code&#39; =&gt; $otp]);<br><br>    return response()-&gt;json([&#39;message&#39; =&gt; &#39;OTP sent successfully&#39;]);<br>}</pre><p>Step VI: In your controller, use the verifyOTP function to verify the OTP entered by the user. For example:</p><pre>use Mckenziearts\LaravelOTP\Facades\OTP;<br><br>public function verifyOTP(Request $request)<br>{<br>    $otp = $request-&gt;input(&#39;otp&#39;);<br><br>    if (OTP::verify($otp)) {<br>        // OTP is valid<br>        return response()-&gt;json([&#39;message&#39; =&gt; &#39;OTP verified successfully&#39;]);<br>    } else {<br>        // OTP is invalid<br>        return response()-&gt;json([&#39;error&#39; =&gt; &#39;Invalid OTP&#39;], 401);<br>    }<br>}</pre><p>That’s it! You have now implemented OTP verification in your Laravel application. You can also customize the OTP expiration time, retry count, and other settings by modifying the package’s configuration file.</p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=541acf320fd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important Lessons that I learned from the book “Atomic Habits” by James Clear.]]></title>
            <link>https://medium.com/@pawanrijal/important-lessons-that-i-learned-from-the-book-atomic-habits-by-james-clear-62ee4222599d?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ee4222599d</guid>
            <category><![CDATA[atomic-habit]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[summary]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[nonfiction]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Tue, 03 May 2022 14:03:11 GMT</pubDate>
            <atom:updated>2022-05-03T14:03:11.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QUGOZ7rwNITrB1IrByb_Q.jpeg" /></figure><blockquote><strong>“To write a book you must first become the book”</strong></blockquote><p>From the above statement, the writer had experienced and made a huge advantage by the methods which he had specified in this book. Now I am going to summarize those tips which I have learned, implemented, and make a great advantage of them.</p><p><strong>Why do tiny changes make huge differences?</strong></p><p>Too often we think that great success in your life requires great action resulting towards it. But that is not the case, when we do action very small but repetitively it can generate greater results in the future.</p><p>According to the book, there is a rule called “<strong>aggregation of marginal gains</strong>” to describe why tiny changes make huge differences. Imagine a scenario, if you have a goal like losing your weight then you would not get fit by exercising continuously from morning to evening in a day. You should start by doing small things like exercising for 10 minutes at the time that suits you best (i recommend early morning). Habits are like the compound interest of self-improvement. Getting 1 percent every day counts for a lot in the long run.</p><p><strong>How to build better habits in 4 simple steps?</strong></p><p>The process of building a habit can be divided into four simple steps: cue, craving, response, and reward.</p><p>The writer divided the above steps of building better habits into two categories</p><ol><li>Problem Phase</li></ol><ul><li>Cue: Your phone vibrates with a notification.</li><li>Craving: You want to see about the notification.</li></ul><p>2. Solution Phase</p><ul><li>Response: You take your phone and read the notification.</li><li>Reward: You satisfy your craving to read the message.</li></ul><p>Taking your phone is associated with your phone buzzing.</p><ol><li><strong>Cue: Make it obvious</strong></li></ol><ul><li>By doing a certain task repetitively your brain picks up doing the task repetitively and predicts outcomes automatically.</li><li>The two most common cues are time and location. You should do your work at a certain time and certain location repetitively to adjust your brain to do the task automatically.</li><li>Your habits will trigger with the context of your environment.</li><li>If you want to remove your bad habit then you should reduce the exposure to the cue that causes it.</li></ul><p><strong>2. Craving: Make it attractive</strong></p><ul><li>The more attractive an action is, the more likely it is to become habit-forming.</li><li>Temptation building is one way to make your habits attractive. The strategy is to pair an action you want to do with an action you need to do.</li><li>Increase your dopamine level in your brain by doing the things you love to do. Habits are a dopamine-driven feedback loop.</li></ul><p><strong>3. Response: Make it easy</strong></p><ul><li>You should make your habit easy don’t focus on the planning of the habit instead focus on the practice and taking action.</li><li>Human behavior follows the law of least effort where we will naturally gravitate toward the option which requires less amount of work.</li></ul><p><strong>4. Reward: Make it satisfying</strong></p><ul><li>The chance of repeating a work when the experience to do the work is satisfying.</li><li>One of the most satisfying feelings is the feeling of making progress, so you should make habit of tracking your progress so that it can satisfy your progress in your work.</li><li>Do not break the chain of your habit. If you miss once but don’t miss twice, try to get back on track with your habit as soon as possible.</li></ul><p><strong>These are the lessons that I learned from the book. I hope you find what you are looking for. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ee4222599d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to use Node JS and When not to?]]></title>
            <link>https://medium.com/@pawanrijal/when-to-use-node-js-and-when-not-to-fe2d7a4f02b4?source=rss-ac132b921370------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe2d7a4f02b4</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Pawan Rijal]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 06:29:32 GMT</pubDate>
            <atom:updated>2022-02-19T06:29:32.717Z</atom:updated>
            <content:encoded><![CDATA[<p>Node JS is a JavaScript runtime built on Chrome V8 engine. It is mainly used for non-blocking, event driven servers due to its single threaded nature.</p><p>Here are important points which you can consider to use Node JS.</p><p><strong>1.For Streaming Web Apps.</strong></p><p>Node is a good choice for the development of streaming apps. The data is sent to frontend from server piece by piece instead of sending a big package. This process allows you to process files while they are being uploaded and can be easily loaded in the frontend.</p><p><strong>2.For building real-time collaboration tools.</strong></p><p>We can use Web sockets for event driven real-time processing between clients in Node JS. So we can use features like state synchronizations to build collaborative web apps.</p><p><strong>3.When building complex, single page web applications.</strong></p><p>Single page applications run on browser and JS is the only language supported by browsers. So we can use Node JS on the backend since it allows for fewer context switches while also enabling server side rendering of single page applications(SPA).</p><p><strong>4.For building microservices architecture.</strong></p><p>When it comes for building microservices majority of developers use Node JS .It is necessary to convert a large structure of applications into small pieces. This helps for applications to run smoothly and high scalability. In microservice architecture the services are interconnected and have better performance when constructed with a functional combinations of APIs.</p><p>Here are points to consider when not to use Node JS.</p><ol><li><strong>For building CPU intensive tasks.</strong></li></ol><p>When it comes to heavy computations Node JS is really a bad idea. Node JS uses event-driven, non-blocking IO model using a single thread. Hence all intense CPU activity will block all the incoming requests. The benefits of Node JS would get nullified in context of CPU-intensive operations.</p><p>So these above listed points are to be considered when to use Node JS and when not to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe2d7a4f02b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>