<?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 Laxman Giri on Medium]]></title>
        <description><![CDATA[Stories by Laxman Giri on Medium]]></description>
        <link>https://medium.com/@laxman.giri?source=rss-3c654768f357------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2dQZw-6O4uYlr4nj</url>
            <title>Stories by Laxman Giri on Medium</title>
            <link>https://medium.com/@laxman.giri?source=rss-3c654768f357------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:28:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@laxman.giri/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[Different Ways To Protect Routes In NextJS]]></title>
            <link>https://medium.com/@laxman.giri/different-ways-to-protect-routes-in-nextjs-ab6dffed8e26?source=rss-3c654768f357------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab6dffed8e26</guid>
            <dc:creator><![CDATA[Laxman Giri]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 08:53:54 GMT</pubDate>
            <atom:updated>2024-01-27T08:53:54.045Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s build a simple Next.js app to gain a practical understanding of route protection. Given that Next.js renders content on both the client and server sides, it’s crucial to understand both server-side and client-side route protection. In this article, we will explore the most commonly used and practical concepts applicable to real-world projects.</p><p>Let’s generate a Next.js app using the following command:</p><pre>npx create-next-app@latest</pre><p>Once you run the above command, you’ll be prompted with a series of questions. Make sure to answer them accordingly to avoid any errors on your end.</p><p>Here is a single image indicating the options I selected (highlighted in green) for this project. In this article, our primary focus is on route protection rather than the step-by-step process of creating a Next.js app. Assuming everyone has successfully set up their Next.js app on their local machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*HJTg6Lqp4ly1no-pT4yMRA.png" /></figure><p>Initially, let’s establish the essential prerequisites for our app. We’ll begin by creating a navbar component.</p><pre>&quot;use client&quot;;<br><br>import React from &quot;react&quot;;<br>import Link from &quot;next/link&quot;;<br><br>const Navbar = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;ul&gt;<br>        &lt;Link href=&quot;/&quot;&gt;<br>          &lt;li&gt;Home&lt;/li&gt;<br>        &lt;/Link&gt;<br>        &lt;Link href=&quot;hoc&quot;&gt;<br>          &lt;li&gt;Client Side with HOC&lt;/li&gt;<br>        &lt;/Link&gt;<br>        &lt;Link href=&quot;middleware&quot;&gt;<br>          &lt;li&gt;Middleware&lt;/li&gt;<br>        &lt;/Link&gt;<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Navbar;</pre><p>Once the navbar component is created, we’ll import it into the layout page as we intend to display it on every page of the project. Below is the complete code for the layout.tsx page.</p><pre>import type { Metadata } from &quot;next&quot;;<br>import { Inter } from &quot;next/font/google&quot;;<br>import &quot;./globals.css&quot;;<br>import Navbar from &quot;../components/Navbar&quot;;<br><br>const inter = Inter({ subsets: [&quot;latin&quot;] });<br><br>export const metadata: 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>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;div className=&quot;mx-auto max-w-5xl text-2xl gap-2 mb-10&quot;&gt;<br>        &lt;Navbar /&gt;<br>        &lt;body className={inter.className}&gt;{children}&lt;/body&gt;<br>      &lt;/div&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>After updating the layout.tsx file, the next step involves checking the user’s status. For the purposes of this demo project, we’ll use a boolean variable to play around with whether the user is authenticated or not. In a real-world scenario, you would typically fetch user data from an API and store it in a variable. The code snippet below illustrates how I created a boolean variable in the session.ts file. This boolean variable (isUserAuthenticated) will be utilized to manage the user&#39;s authentication status within the application.</p><pre>export const isUserAuthenticated: boolean = false;</pre><p>Once these setups are complete, the next step involves creating two pages named “hoc” and “middleware.” The content of these pages will render a div and nothing more.</p><pre>&quot;use client&quot;;<br><br>import React from &quot;react&quot;;<br><br>const Hoc = () =&gt; {<br>  return &lt;div&gt;This is high order component&lt;/div&gt;;<br>};<br><br>export default Hoc;</pre><pre>&quot;use client&quot;;<br><br>import React from &quot;react&quot;;<br><br>const Middleware = () =&gt; {<br>  return &lt;div&gt;This is middleware component&lt;/div&gt;;<br>};<br><br>export default Middleware;</pre><p>Now, we dive into the actual implementation of route protection using two approaches:</p><ol><li>Protecting Routes with High Order Component (HOC).</li><li>Protecting Routes with Middleware.</li></ol><p>Let’s explore and implement these methods for route protection.</p><ol><li>HOC</li></ol><p>In the context of React, a High Order Component (HOC) is a function that takes a component and returns a new component with additional props or modified behavior. It is a way to reuse component logic and share it among different parts of your application.</p><p>For route protection, an HOC can be used to wrap components that require authentication. The HOC can check the user’s authentication status and either render the component if the user is authenticated or redirect to a home page if the user is not authenticated.</p><p>Here’s a basic example of an authentication HOC:</p><pre>&quot;use client&quot;;<br>import { useEffect } from &quot;react&quot;;<br>import { isUserAuthenticated } from &quot;../session&quot;;<br>import { redirect } from &quot;next/navigation&quot;;<br><br>export const withAuth = (WrappedComponent: any) =&gt; {<br>  return function WithAuth(props: any) {<br>    const session = isUserAuthenticated;<br>    useEffect(() =&gt; {<br>      if (!session) {<br>        redirect(&quot;/&quot;);<br>      }<br>    }, []);<br><br>    if (!session) {<br>      return null;<br>    }<br>    return &lt;WrappedComponent {...props} /&gt;;<br>  };<br>};</pre><p>Usage of this HOC in a page component:</p><pre>&quot;use client&quot;;<br>import { withAuth } from &quot;@/components/withAuth&quot;;<br>import React from &quot;react&quot;;<br><br>const HOC = () =&gt; {<br>  return &lt;div&gt;HOC&lt;/div&gt;;<br>};<br><br>export default withAuth(HOC);</pre><p>In this example, the withAuth HOC wraps the HOC component. If the user is authenticated, the HOC component will be rendered; otherwise, user will be redirected to a home page.</p><p>2. Middleware</p><p>Here the middleware will perform the same task of checking whether the user is authenticated and, if not, redirecting to the home page. The protected routes are stored in an array named protectedRoutes, and the user&#39;s authentication status is determined using isUserAuthenticated. If the user is authenticated, they will be directed to the next page; otherwise, they will be redirected to the home page. Here’s the middleware implementation:</p><pre>import { isUserAuthenticated } from &quot;@/session&quot;;<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br><br>const protectedRoutes = [&quot;/middleware&quot;];<br>export default function middleware(req: NextRequest) {<br>  if (<br>    !isUserAuthenticated &amp;&amp;<br>    protectedRoutes.includes(req?.nextUrl?.pathname)<br>  ) {<br>    const absoluteUrl = new URL(&quot;/&quot;, req.nextUrl.origin);<br>    return NextResponse.redirect(absoluteUrl.toString());<br>  }<br>  return NextResponse.next();<br>}</pre><p>I hope this article will help you in getting started with route protection in nextjs. Thank You 🙇. <br><a href="https://github.com/Girilaxman000/route-protection">https://github.com/Girilaxman000/route-protection</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab6dffed8e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[App Router vs Page Router in nextjs]]></title>
            <link>https://medium.com/@laxman.giri/app-router-vs-page-router-in-nextjs-b911a84d3a9d?source=rss-3c654768f357------2</link>
            <guid isPermaLink="false">https://medium.com/p/b911a84d3a9d</guid>
            <dc:creator><![CDATA[Laxman Giri]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 07:28:03 GMT</pubDate>
            <atom:updated>2023-10-02T11:17:47.438Z</atom:updated>
            <content:encoded><![CDATA[<p>Beginning with Next.js 13, we have two options for routing management: the app router and the page router. The distinctions between these two approaches are described below:</p><ol><li>App’s structure</li></ol><p>In the page router within the “pages” directory, our app takes on the following structure, where certain pre-generated pages like _app.tsx, _document.tsx, and index.tsx are included. To define new pages for our app, it&#39;s as straightforward as naming them accordingly. For instance, creating pages like &quot;login.tsx&quot; and &quot;register.tsx&quot; is all that&#39;s needed to add these pages to our application:</p><figure><img alt="structure" src="https://cdn-images-1.medium.com/max/192/1*suTZP8aY1hUEPGbqJMZu9Q.png" /></figure><p>Within the “app” directory, our app adopts the following structure, as shown in an image. This structure includes pregenerated files such as favicon.ico, globals.css, layout.tsx, and page.tsx. To create new pages for our app, follow these steps:</p><ol><li>Start by creating a folder with your desired page name.</li><li>Inside this folder, include a file named page.tsx, which will serve as the basis for creating the new page.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*KceiE59Cg5PIhL-uZSG_0Q.png" /></figure><p>2. Routing and navigation</p><p>The Page directory employs client-side routing, enabling seamless navigation between different pages of your application on the client side without the need for a full server request for each page transition whereas the App Router employs server-centric routing, which eliminates the need to download the route map to the client. Instead, it stores the payload of React server components in an in-memory cache, significantly enhancing routing speed.</p><p>3. Data fetching<br>By default everything is a react server component. With app router next gives an ability to use async await inside of our component if we are using RSC</p><p>With app router we can directly fetch data in server side using async await.</p><p>4. layout.tsx</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b911a84d3a9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointers in Golang]]></title>
            <link>https://medium.com/@laxman.giri/pointers-in-golang-aa4bf54b768f?source=rss-3c654768f357------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa4bf54b768f</guid>
            <dc:creator><![CDATA[Laxman Giri]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 10:21:05 GMT</pubDate>
            <atom:updated>2023-08-29T11:51:50.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Before understanding pointers in Golang, let’s get a brief grasp of variable. Variable is made up of keyword , name, type and value.</p><pre>var age int = 20</pre><p>Here keyword is var , variable name is age, it’s type is int and it’s value is 20. This composition is stored in computer’s memory with its unique address. For finding the address of variable inside memory we do (&amp;) followed by variable name. Here (&amp;) is an operator which is commonly known as address of.</p><pre>package main<br>import &quot;fmt&quot;<br><br>func main() {<br>    var age int = 20<br>    fmt.Println(age) // prints the value<br>    fmt.Println(&amp;age) // prints the memory address<br>}</pre><h4><strong>Pointers</strong></h4><ol><li>Declaration</li></ol><p>Now let’s jump to pointer concept. Pointer is a variable which stores memory address of another variable. We can access and modify the values of variables in the memory using pointers. Pointer declaration is same as normal variable. Let’s initialize a pointer.</p><pre>var agePointer *int</pre><p>Here, keyword is var, variable name is agePointer and it’s type is pointer to an integer. After initializing variable let’s store some value inside it.</p><pre>var age int = 20<br>var agePointer *int <br>agePointer = &amp;age</pre><p>2. Dereferencing</p><p>After storing the memory address of the age variable in the agePointer, you can use the pointer to access the value stored in that memory location. This process is known as &quot;dereferencing&quot; the pointer. Here&#39;s how you can do it by simplying placing (*) before variable name agePointer:</p><pre>fmt.Println(*agePointer)</pre><p>Let’s summarize the above discussion in code.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    var age int = 20<br>    var agePointer *int   // declare a pointer to an int<br>    agePointer = &amp;age     // assign the address of age to the pointer<br>    fmt.Println(*agePointer)   // prints the value pointed to by the pointer<br>    fmt.Println(agePointer)    // prints the memory address stored in the pointer<br>}</pre><h3>Why Pointer?</h3><ol><li>Passing References</li></ol><p>Go uses pass-by-value for function arguments, which means that when you pass an argument to a function, a copy of the value is made. However, sometimes you might want to modify the original value inside a function. Pointers enable you to pass a reference to a variable, allowing the function to modify the original value. The below two examples verify above statement.</p><ol><li>1. Without Pointer</li></ol><p>Here the function receives User struct by value which means a copy of User struct is sent to updateStructAge. So any modifications made to the struct within the updateStructAge function only affect the copy inside the function’s scope, and these changes aren’t reflected in main function.</p><pre>package main<br>import &quot;fmt&quot;<br><br>//define struct<br>type User struct {<br>    age int<br>}<br><br>// no pointer of struct<br>func (u User) updateStructAge(val int) {<br>    u.age = val // This changes the age in the copy of the User struct not original one because we are passing copy of struct user.<br>}<br><br>func main() {<br>    // Struct<br>    user := User{age: 20}<br>    user.updateStructAge(40) // This doesn&#39;t change the original &#39;user&#39; struct<br>    fmt.Println(user.age)    // Prints 20 because the original &#39;user&#39; was not modified<br>}</pre><ol><li>2. With Pointer</li></ol><p>So for changing value of age inside User struct pointer plays a vital role. When a pointer to the User struct is passed, we receive the memory address of the struct. Any change made to the age field will directly affect this memory address, reflecting the change across all that reference this memory location.</p><pre>package main<br>import &quot;fmt&quot;<br><br>type User struct {<br>    age int<br>}<br><br>//pointer to struct User<br>func (u *User) updateStructPointerAge(val int) {<br>    u.age = val // This changes the age of the original User struct.<br>}<br><br>func main() {<br>    // Struct<br>    user := User{age: 20}<br>    user.updateStructPointerAge(40) // This changes original struct<br>    fmt.Println(user.age)    // Prints 40 because the original &#39;user&#39; was modified<br>}</pre><blockquote>The difference between the two code snippets is how they receive the User struct as a parameter. The first function receives the User struct by value, while the second function receives it by a pointer.</blockquote><p>2. Memory Optimization</p><p>While Go abstracts much of the complexity of pointers, using pointers when necessary can help reduce memory consumption. For example, use pointers for large struct types that you pass around frequently, instead of copying the entire struct. Pointers are integers that store the value of the memory address. Being integers, they only take up 4 bytes on a 32 bit system, or 8 bytes on a 64 bit system. Which is way less than the 64 bytes (or potentially may increase in future) that our User struct takes up.</p><p>2.1. Without Pointer</p><p>Here, the unsafe function is utilized to determine the size of the User struct. When a copy of the user struct is passed as parameters to the updateStructName function, its size remains at 64 bytes, potentially increasing with any growth in the User struct. To address this issue, pointers are employed as a solution.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;unsafe&quot;<br>)<br><br>type User struct {<br> age [2]int<br> name string<br> email string<br> password string<br>}<br><br>func (u User) updateStructName(val int) {<br> fmt.Printf(&quot;Size of User struct: %d bytes\n&quot;, unsafe.Sizeof(u))<br> u.age[0] = val // Doesn&#39;t modify original struct<br>}<br><br><br>func main() {<br> // Struct<br> user := User{age: [2]int{20, 12}, name: &quot;laxman&quot;, email: &quot;laxa&quot;, password: &quot;dashd&quot;}<br> user.updateStructName(40) // This deosn&#39;t modifies the original &#39;user&#39; struct<br> fmt.Println(user.age)     // Prints [20 12] because the original &#39;user&#39; was modified<br><br> <br>}</pre><p>2.2. With Pointer</p><p>Here, pointers came in handy for memory management. Whatever the size of User struct is passed as params to updateStructName function, the size of pointer to User struct remains constant at 4 bytes on a 32 bit system or 8 bytes on a 64 bit system. So because of this reason pointers are preferred for memory management. The code below clarifies your doubt in detail.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;unsafe&quot;<br>)<br><br>type User struct {<br> age [2]int<br> name string<br> email string<br> password string<br>}<br><br>func (u *User) updateStructName(val int) {<br> fmt.Printf(&quot;Size of User struct: %d bytes\n&quot;, unsafe.Sizeof(u))<br> u.age[0] = val // Modifies the age in the original &#39;User&#39; struct because we&#39;re using a pointer receiver<br>}<br><br><br>func main() {<br> // Struct<br> user := User{age: [2]int{20, 12}, name: &quot;laxman&quot;, email: &quot;laxa&quot;, password: &quot;dashd&quot;}<br> user.updateStructName(40) // This modifies the original &#39;user&#39; struct<br> fmt.Println(user.age)     // Prints [40 12] because the original &#39;user&#39; was modified<br>}</pre><blockquote>Here, when a struct is passed by value, a copy of the entire struct is created, which includes all its fields. However, when a struct is passed by a pointer, only the memory address of the original struct is passed, not a copy of the entire struct. This distinction affects the memory usage and can lead to differences in memory size.</blockquote><p>3. Nil pointer</p><p>Pointers can be used to represent the absence of a value. Instead of using a specific default value (like 0 or empty string) to indicate absence, you can use a nil pointer to clearly signify that no valid value is present. In int case, 0 is typically used as the numeric value zero. It&#39;s a numeric value, not a representation of absence. It&#39;s not semantically appropriate to use 0 to convey the absence of a reference or the absence of a value in a pointer. So, pointer is used for conveying an absence.</p><p>For instance, consider a gaming scenario where users are prompted to choose a random number. In this situation, using pointers proves beneficial. If a user doesn’t make a selection, the default value could be mistaken for a valid choice. By employing pointers, we can elegantly handle cases where users haven’t made a selection, ensuring that absence is represented without confusion.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func getUserPreferredNumber(userID int) *int {<br> // In this example, we&#39;ll assume users haven&#39;t selected any number yet.<br> return nil // Return a nil pointer to indicate the absence of a selected number.<br>}<br><br>func main() {<br> userID := 789<br> preferredNumber := getUserPreferredNumber(userID)<br><br> if preferredNumber == nil {<br>  fmt.Println(&quot;User with ID&quot;, userID, &quot;has no preferred number.&quot;)<br> } else {<br>  fmt.Println(&quot;User&#39;s preferred number is:&quot;, *preferredNumber)<br> }<br>}</pre><p>Conclusion:</p><p>Hope this article helps you for clearing concept of pointer in Golang.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa4bf54b768f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>