<?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"><channel><title><![CDATA[Bibek's Blog]]></title><description><![CDATA[A skilled software engineer, talented problem-solver and team player with a passion for using technology to solve complex problems and constantly seeking out ne]]></description><link>https://blog.bibekkakati.me</link><generator>RSS for Node</generator><lastBuildDate>Sat, 18 Apr 2026 00:49:52 GMT</lastBuildDate><atom:link href="https://blog.bibekkakati.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Build a Classic Snake Game Using React.js]]></title><description><![CDATA[Hello folks! Welcome to this tutorial on developing the classic Snake game using ReactJS.
I've been working with technology for over six years now, but I've never tried building a game that many of us loved during our childhood. So, this weekend, I d...]]></description><link>https://blog.bibekkakati.me/how-to-build-a-classic-snake-game-using-reactjs</link><guid isPermaLink="true">https://blog.bibekkakati.me/how-to-build-a-classic-snake-game-using-reactjs</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[snake game]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Game Development]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Mon, 03 Jun 2024 19:30:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717442617107/41bb8909-65c5-499b-9a89-e173c2c0cb40.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello folks! Welcome to this tutorial on developing the classic Snake game using ReactJS.</p>
<p>I've been working with technology for over six years now, but I've never tried building a game that many of us loved during our childhood. So, this weekend, I decided to create this classic Snake game using web technologies, specifically ReactJS.</p>
<p>Before proceeding further, let me clarify what we are building. As we know, there are various versions of the Snake game available on the internet. What we are building is a game board where the snake will move at a constant speed in the user-selected direction. When it consumes a food ball, its length will increase, and a point will be scored. If the snake's head touches the wall boundary or any part of its own body, the game is over.</p>
<p>Github: <a target="_blank" href="https://github.com/bibekkakati/snake-game-web">https://github.com/bibekkakati/snake-game-web</a></p>
<p>Demo: <a target="_blank" href="https://snake-ball.netlify.app">https://snake-ball.netlify.app</a></p>
<h2 id="heading-game-design">Game Design</h2>
<h3 id="heading-components-in-the-game">Components in the game</h3>
<ul>
<li><p>Snake</p>
</li>
<li><p>Food Ball</p>
</li>
<li><p>Game Board</p>
</li>
<li><p>Boundary Walls</p>
</li>
</ul>
<h3 id="heading-approach">Approach</h3>
<ul>
<li><p>The game board is a 2D matrix with multiple rows and columns.</p>
</li>
<li><p>The intersection of rows and columns forms a cell.</p>
</li>
<li><p>A cell can be identified by its row number and column number.</p>
</li>
<li><p>The snake's body parts will be represented by these cell numbers on the board.</p>
</li>
<li><p>When the snake moves, the cell number (i.e., row and column number) will be updated for the body part cell based on the direction. For example, if the snake is moving to the right, the cell's column number will be incremented by 1.</p>
</li>
<li><p>Before rendering the snake's position after each movement, we also need to perform these steps:</p>
<ul>
<li><p>Check if this movement results in any collision with the boundary wall or its own body. If there is a collision, stop the game and show "game over"; otherwise, continue.</p>
</li>
<li><p>Check if the snake's head cell number is the same as the food ball's cell number. If they match, update the score and place a new food ball on the board.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-implementation">Implementation</h2>
<p>We are writing all the logic and UI code in a single file, <code>App.jsx</code>, and using <code>index.css</code> for the styling. In this implementation, we will not be discussing the styling.</p>
<h3 id="heading-constants">Constants</h3>
<p>First, we will declare the constants before the component function definition.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> COLs = <span class="hljs-number">48</span>; <span class="hljs-comment">// Number of columns on board</span>
<span class="hljs-keyword">const</span> ROWs = <span class="hljs-number">48</span>; <span class="hljs-comment">// Number of rows on board</span>

<span class="hljs-comment">// Default length of snake i.e, it will consume 10 cell by default</span>
<span class="hljs-keyword">const</span> DEFAULT_LENGTH = <span class="hljs-number">10</span>;

<span class="hljs-comment">// Declaring directions as symbol for equality checks</span>
<span class="hljs-keyword">const</span> UP = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"up"</span>);
<span class="hljs-keyword">const</span> DOWN = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"down"</span>);
<span class="hljs-keyword">const</span> RIGHT = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"right"</span>);
<span class="hljs-keyword">const</span> LEFT = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"left"</span>);
</code></pre>
<h3 id="heading-state-and-reference">State and Reference</h3>
<p>Declare the reference and state variables.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> timer = useRef(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">const</span> grid = useRef(<span class="hljs-built_in">Array</span>(ROWs).fill(<span class="hljs-built_in">Array</span>(COLs).fill(<span class="hljs-string">""</span>)));
<span class="hljs-keyword">const</span> snakeCoordinates = useRef([]);
<span class="hljs-keyword">const</span> direction = useRef(RIGHT);
<span class="hljs-keyword">const</span> snakeCoordinatesMap = useRef(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>());
<span class="hljs-keyword">const</span> foodCoords = useRef({
    <span class="hljs-attr">row</span>: <span class="hljs-number">-1</span>,
    <span class="hljs-attr">col</span>: <span class="hljs-number">-1</span>,
});
<span class="hljs-keyword">const</span> [points, setPoints] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> [gameOver, setGameOver] = useState(<span class="hljs-literal">false</span>);
<span class="hljs-keyword">const</span> [isPlaying, setPlaying] = useState(<span class="hljs-number">0</span>);
</code></pre>
<ul>
<li><p>The <code>timer</code> variable stores the instance of <code>setInterval</code> that we use to automate the snake's movement. This instance will be used to clear the interval when the game is over.</p>
</li>
<li><p>The <code>grid</code> variable stores the empty 2D array used to render the game board.</p>
</li>
<li><p>The <code>snakeCoordinates</code> variable stores the indexes of the snake's body parts, i.e., cell numbers. The <code>0th</code> index value is the snake's tail, and the last value is the snake's head.</p>
<ul>
<li>The value of snake coordinates will look like <code>{ row: [Number], col: [Number], isHead: [Boolean] }</code>.</li>
</ul>
</li>
<li><p>The <code>direction</code> variable stores the user-selected direction. This value will be the same as the declared constant direction symbols.</p>
</li>
<li><p>The <code>snakeCoordinatesMap</code> variable stores the set of snake body parts, i.e., cell numbers. This helps in the render method to check which part of the board (grid) we need to render a snake body part on. The variable name includes the word <code>map</code>, but the value is of type <code>Set</code>.</p>
</li>
<li><p>The <code>foodCoords</code> variable stores the position of the food ball's cell number.</p>
</li>
<li><p>The <code>points</code>, <code>gameOver</code>, and <code>isPlaying</code> are state variables used to store the score, game over status, and game play status, respectively.</p>
</li>
</ul>
<blockquote>
<p>You might have noticed that <code>isPlaying</code> is a number, not a boolean. This is due to a specific bypass mechanism we will discuss in the coming sections.</p>
</blockquote>
<h3 id="heading-functionality">Functionality</h3>
<p>Let's discuss the implementation of snake's body movement along with collision check and food ball consumption.</p>
<p>We are writing a function <code>moveSnake</code> to handle the snake movement logic.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moveSnake = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (gameOver) <span class="hljs-keyword">return</span>;

        setPlaying(<span class="hljs-function">(<span class="hljs-params">s</span>) =&gt;</span> s + <span class="hljs-number">1</span>);

        <span class="hljs-keyword">const</span> coords = snakeCoordinates.current;
        <span class="hljs-keyword">const</span> snakeTail = coords[<span class="hljs-number">0</span>];
        <span class="hljs-keyword">const</span> snakeHead = coords.pop();
        <span class="hljs-keyword">const</span> curr_direction = direction.current;

        <span class="hljs-comment">// Check for food ball consumption</span>
        <span class="hljs-keyword">const</span> foodConsumed =
            snakeHead.row === foodCoords.current.row &amp;&amp;
            snakeHead.col === foodCoords.current.col;

        <span class="hljs-comment">// Update body coords based on direction and its position</span>
        coords.forEach(<span class="hljs-function">(<span class="hljs-params">_, idx</span>) =&gt;</span> {
            <span class="hljs-comment">// Replace last cell with snake head coords [last is the cell after snake head]</span>
            <span class="hljs-keyword">if</span> (idx === coords.length - <span class="hljs-number">1</span>) {
                coords[idx] = { ...snakeHead };
                coords[idx].isHead = <span class="hljs-literal">false</span>;
                <span class="hljs-keyword">return</span>;
            }

            <span class="hljs-comment">// Replace current cell coords with next cell coords</span>
            coords[idx] = coords[idx + <span class="hljs-number">1</span>];
        });

        <span class="hljs-comment">// Update snake head coords based on direction</span>
        <span class="hljs-keyword">switch</span> (curr_direction) {
            <span class="hljs-keyword">case</span> UP:
                snakeHead.row -= <span class="hljs-number">1</span>;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> DOWN:
                snakeHead.row += <span class="hljs-number">1</span>;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> RIGHT:
                snakeHead.col += <span class="hljs-number">1</span>;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> LEFT:
                snakeHead.col -= <span class="hljs-number">1</span>;
                <span class="hljs-keyword">break</span>;
        }

        <span class="hljs-comment">// If food ball is consumed, update points and new position of food</span>
        <span class="hljs-keyword">if</span> (foodConsumed) {
            setPoints(<span class="hljs-function">(<span class="hljs-params">points</span>) =&gt;</span> points + <span class="hljs-number">10</span>);
            populateFoodBall();
        }

        <span class="hljs-comment">// If there is no collision for the movement, continue the game</span>
        <span class="hljs-keyword">const</span> collided = collisionCheck(snakeHead);
        <span class="hljs-keyword">if</span> (collided) {
            stopGame();
            <span class="hljs-keyword">return</span>;
        }

        <span class="hljs-comment">// Create new coords with new snake head</span>
        coords.push(snakeHead);
        snakeCoordinates.current = foodConsumed
            ? [snakeTail, ...coords]
            : coords;
        syncSnakeCoordinatesMap(); <span class="hljs-comment">// Function to create a set from snake body coordinates</span>
    };
</code></pre>
<ul>
<li><p>The first check ensures that if the game is over, we don't need to move the snake. It's just an extra precaution.</p>
</li>
<li><p>Next, we derive the current snake coordinates, the snake tail position, and the snake head position.</p>
</li>
<li><p>We then check if the food ball is consumed, meaning the snake head position should match the food ball position.</p>
</li>
<li><p>After that, we iterate over the body parts, excluding the snake head, to determine the new coordinates of the snake body.</p>
<ul>
<li><p>The position of each snake body part depends on the position of the next part, as the snake's body parts move in the same path as the head. So, we replace the current body part coordinates with the next body part's coordinates.</p>
</li>
<li><p>If the body part is the last one, i.e., the neck, it will take the coordinates of the current snake head.</p>
</li>
</ul>
</li>
<li><p>We then update the new snake head position based on the selected direction.</p>
</li>
<li><p>Finally, we check for food consumption and collisions and update the new snake coordinates if there is no collision.</p>
</li>
</ul>
<p>Let's talk about how we populate the food ball.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> populateFoodBall = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> row = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * ROWs);
        <span class="hljs-keyword">const</span> col = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * COLs);

        foodCoords.current = {
            row,
            col,
        };
    };
</code></pre>
<p>We generate a random row and column number based on our constants and set them in the reference variable <code>foodCoords</code>.</p>
<p>Now, let's discuss the collision check function.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> collisionCheck = <span class="hljs-function">(<span class="hljs-params">snakeHead</span>) =&gt;</span> {
        <span class="hljs-comment">// Check wall collision</span>
        <span class="hljs-keyword">if</span> (
            snakeHead.col &gt;= COLs ||
            snakeHead.row &gt;= ROWs ||
            snakeHead.col &lt; <span class="hljs-number">0</span> ||
            snakeHead.row &lt; <span class="hljs-number">0</span>
        ) {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }

        <span class="hljs-comment">// Check body collision</span>
        <span class="hljs-keyword">const</span> coordsKey = <span class="hljs-string">`<span class="hljs-subst">${snakeHead.row}</span>:<span class="hljs-subst">${snakeHead.col}</span>`</span>;
        <span class="hljs-keyword">if</span> (snakeCoordinatesMap.current.has(coordsKey)) {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }
    };
</code></pre>
<p>The function will receive the new snake head coordinates as a parameter.</p>
<p>First, we check for boundary collisions. If the new snake head's coordinates are greater than the respective constants or less than 0, it means the snake head is going out of range, which is a collision.</p>
<p>Next, we check for self-collision, meaning the snake head colliding with its own body. We do this by checking if the snake head coordinates are already present in the snake coordinates map.</p>
<p>Then we have the <code>startGame</code> and <code>stopGame</code> functions to control the gameplay.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> startGame = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
            moveSnake();
        }, <span class="hljs-number">100</span>);

        timer.current = interval;
    };

    <span class="hljs-keyword">const</span> stopGame = <span class="hljs-keyword">async</span> () =&gt; {
        setGameOver(<span class="hljs-literal">true</span>);
        setPlaying(<span class="hljs-literal">false</span>);
        <span class="hljs-keyword">if</span> (timer.current) {
            <span class="hljs-built_in">clearInterval</span>(timer.current);
        }
    };
</code></pre>
<p><code>startGame</code> triggers a <code>setInterval</code> with a <code>100ms</code> interval. After each interval, the <code>moveSnake</code> method is called.</p>
<p><code>stopGame</code> sets the game over state, updates the gameplay status, and clears the interval instance.</p>
<p>Then, we have the render method.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> getCell = useCallback(
        <span class="hljs-function">(<span class="hljs-params">row_idx, col_idx</span>) =&gt;</span> {
            <span class="hljs-keyword">const</span> coords = <span class="hljs-string">`<span class="hljs-subst">${row_idx}</span>:<span class="hljs-subst">${col_idx}</span>`</span>;
            <span class="hljs-keyword">const</span> foodPos = <span class="hljs-string">`<span class="hljs-subst">${foodCoords.current.row}</span>:<span class="hljs-subst">${foodCoords.current.col}</span>`</span>;
            <span class="hljs-keyword">const</span> head =
                snakeCoordinates.current[snakeCoordinates.current.length - <span class="hljs-number">1</span>];
            <span class="hljs-keyword">const</span> headPos = <span class="hljs-string">`<span class="hljs-subst">${head?.row}</span>:<span class="hljs-subst">${head?.col}</span>`</span>;

            <span class="hljs-keyword">const</span> isFood = coords === foodPos;
            <span class="hljs-keyword">const</span> isSnakeBody = snakeCoordinatesMap.current.has(coords);
            <span class="hljs-keyword">const</span> isHead = headPos === coords;

            <span class="hljs-keyword">let</span> className = <span class="hljs-string">"cell"</span>;
            <span class="hljs-keyword">if</span> (isFood) {
                className += <span class="hljs-string">" food"</span>;
            }
            <span class="hljs-keyword">if</span> (isSnakeBody) {
                className += <span class="hljs-string">" body"</span>;
            }
            <span class="hljs-keyword">if</span> (isHead) {
                className += <span class="hljs-string">" head"</span>;
            }

            <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{col_idx}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{className}</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
        },
        [isPlaying]
    );

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app-container"</span>&gt;</span>
            {gameOver ? (
                <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"game-over"</span>&gt;</span>GAME OVER<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
            ) : (
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{isPlaying</span> ? <span class="hljs-attr">stopGame</span> <span class="hljs-attr">:</span> <span class="hljs-attr">startGame</span>}&gt;</span>
                    {isPlaying ? "STOP" : "START"} GAME
                <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            )}
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"board"</span>&gt;</span>
                {grid.current?.map((row, row_idx) =&gt; (
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{row_idx}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"row"</span>&gt;</span>
                        {row.map((_, col_idx) =&gt; getCell(row_idx, col_idx))}
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                ))}
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"score"</span>&gt;</span>SCORE {points}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
</code></pre>
<p>The <code>getCell</code> method checks if the cell is empty, part of the snake's body, or food, and updates the CSS class name accordingly.</p>
<p>We use the <code>useCallback</code> hook in the <code>getCell</code> method, with <code>isPlaying</code> as a dependency. This <code>isPlaying</code> variable is a number that increases by 1 with each snake movement.</p>
<p>Here's why we did this:</p>
<ol>
<li><p><strong>Stale State Issue:</strong></p>
<ul>
<li><p>Initially, many variables were state variables.</p>
</li>
<li><p>The snake movement logic didn't work well because <code>setInterval</code> was calling <code>moveSnake</code> but the state values inside <code>moveSnake</code> weren't updating properly.</p>
</li>
</ul>
</li>
<li><p><strong>Switch to Reference Variables:</strong></p>
<ul>
<li><p>To fix this, we changed those state variables to reference variables.</p>
</li>
<li><p>This allowed <code>moveSnake</code> to access the latest values.</p>
</li>
</ul>
</li>
<li><p><strong>Re-rendering Problem:</strong></p>
<ul>
<li><p>Reference variables don't trigger re-renders when they change.</p>
</li>
<li><p>To solve this, we used the <code>isPlaying</code> state variable which increments by 1 with each snake movement.</p>
</li>
<li><p>This increment ensures the <code>getCell</code> method has access to the updated reference variable and the component re-renders correctly.</p>
</li>
</ul>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717442733818/8f15d52f-6d4f-43cd-a066-47cd1a2dcf06.png" alt class="image--center mx-auto" /></p>
<p>Github: <a target="_blank" href="https://github.com/bibekkakati/snake-game-web">https://github.com/bibekkakati/snake-game-web</a></p>
<p>Demo: <a target="_blank" href="https://snake-ball.netlify.app">https://snake-ball.netlify.app</a></p>
<blockquote>
<p>Works best on desktop web.</p>
</blockquote>
<hr />
<p>I hope this tutorial helps you understand the concept behind implementing a snake game. There are a few alternative approaches as well, but I found this method easier to understand and implement. Please feel free to share your feedback and suggestions.</p>
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Navigating React.js SEO Challenges]]></title><description><![CDATA[Introduction:
Embarking on the journey of launching CoderKit, a React.js application, brought with it the daunting challenge of Search Engine Optimization (SEO). This blog recounts the SEO hurdles faced and the inventive solutions employed to ensure ...]]></description><link>https://blog.bibekkakati.me/navigating-reactjs-seo-challenges</link><guid isPermaLink="true">https://blog.bibekkakati.me/navigating-reactjs-seo-challenges</guid><category><![CDATA[SEO]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Google]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sun, 19 Nov 2023 16:18:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700410514300/fcb2f991-230f-4107-bf36-4741be3ac0b2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction:</h3>
<p>Embarking on the journey of launching CoderKit, a React.js application, brought with it the daunting challenge of Search Engine Optimization (SEO). This blog recounts the SEO hurdles faced and the inventive solutions employed to ensure visibility on Google.</p>
<h3 id="heading-the-seo-conundrum">The SEO Conundrum:</h3>
<p>Post-launch, the realization struck that the application wasn't making its way to Google search results. Traditional solutions pointed toward static site generators or frameworks like Next.js, but migrating the project wasn't an option. Delving into SEO implementation nuances and website essentials, initial efforts to update meta descriptions in index.html proved futile.</p>
<h3 id="heading-discovering-the-power-of-sitemapxml">Discovering the Power of Sitemap.xml:</h3>
<p>A breakthrough emerged with the revelation of the significance of sitemap.xml. Creating a script to automatically generate this file based on known routes, devoid of dynamic backend-driven URLs, became pivotal. Configuring the Search Console to index these pages marked progress, but a notification soon arrived—indexing failure.</p>
<h3 id="heading-addressing-redirection-woes">Addressing Redirection Woes:</h3>
<p>Upon inspection, the issue lay in redirection. React applications default to landing on index.html, hindering search engines from indexing individual pages. An innovative solution materialized: generating HTML pages for each known route during the pre-build phase. These pages mirrored index.html structure but contained distinct meta tags and content pulled from the route config.</p>
<h3 id="heading-making-redirection-seamless">Making Redirection Seamless:</h3>
<p>Concerns about server-level configurations were assuaged by platforms like Netlify, which inherently checked for file name matches with requested URLs. If found, they returned the file; otherwise, they defaulted to redirecting requests to index.html. This seamless redirection is crucial for React applications, ensuring that custom error components function effectively.</p>
<h3 id="heading-testing-and-triumph">Testing and Triumph:</h3>
<p>With all configurations updated in the Search Console, the real test began. After a day, a notification arrived—success! All pages were now indexed. However, the ranking was modest due to the application's novelty. A search appended with "coderkit" yielded optimal results, but there was room for improvement.</p>
<h3 id="heading-conclusion">Conclusion:</h3>
<p>This SEO journey with CoderKit reflects the iterative and adaptive nature of problem-solving in the tech realm. While the current approach has yielded positive results, the ever-evolving landscape of SEO beckons exploration. Feedback and alternative approaches are welcomed. Check out <a target="_blank" href="https://coderkit.dev">CoderKit</a> to witness these strategies in action.</p>
]]></content:encoded></item><item><title><![CDATA[Unleash Your Coding Superpowers with CoderKit! 🚀]]></title><description><![CDATA[🚀 The Spark of Inspiration
As a developer, I've been there, facing those repetitive coding tasks day in and day out. That's when the spark ignited. I asked myself, "How can we make this easier?"
💡 The Eureka Moment
And just like that, CoderKit was ...]]></description><link>https://blog.bibekkakati.me/unleash-your-coding-superpowers-with-coderkit</link><guid isPermaLink="true">https://blog.bibekkakati.me/unleash-your-coding-superpowers-with-coderkit</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[tools]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sat, 04 Nov 2023 05:30:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1699040748718/26d48564-dbaa-49b9-a0fe-1a655bebb269.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>🚀 <strong>The Spark of Inspiration</strong></p>
<p>As a developer, I've been there, facing those repetitive coding tasks day in and day out. That's when the spark ignited. I asked myself, "How can we make this easier?"</p>
<p>💡 <strong>The Eureka Moment</strong></p>
<p>And just like that, CoderKit was born. I dreamt of a toolbox filled with developer-friendly utilities. A JSON formatter, a text case converter, a code minifier and more – all at your fingertips.</p>
<p>🛠️ <strong>Building the Arsenal</strong></p>
<p>The journey was a rollercoaster, crafting tools, and making them work seamlessly. It was just me and my code, hours upon hours. The tools became my coding companions.</p>
<p>👥 <strong>Inviting You to the Journey</strong></p>
<p>Today, we're launching CoderKit Beta. It's about time we made your coding life simpler. These tools are designed to make your day-to-day coding tasks a breeze.</p>
<p>🤝 <strong>Your Feedback, Our Fuel</strong></p>
<p>CoderKit isn't complete without you. Your feedback, and your insights – they're our guiding stars. This Beta launch is the beginning, and your suggestions will shape the future.</p>
<p>🔮 <strong>The Future of Coding</strong></p>
<p>CoderKit is not just about tools; it's about coding with confidence. We're here to empower you – whether you're a pro or just starting.</p>
<p>🌐 <strong>Join the Journey</strong></p>
<p>Come, and explore CoderKit Beta with us. Try out the tools, and share your thoughts. Let's make coding a bit more exciting.</p>
<p>🔧 <strong>Meet the Tools</strong></p>
<ul>
<li><p>JSON Formatter: Tame unruly JSON data with ease, ensuring readability and error-free code.</p>
</li>
<li><p>Text Case Converter: Convert text between various cases (e.g., CamelCase, snake_case) effortlessly.</p>
</li>
<li><p>JavaScript Minifier: Reduce file size and boost website performance by minifying your JavaScript code.</p>
</li>
<li><p>HTML Minifier: Optimize your HTML code for faster loading times and improved user experience.</p>
</li>
<li><p>CSS Minifier: Streamline your stylesheets to enhance website performance.</p>
</li>
<li><p>JavaScript Beautifier: Make your JavaScript code more readable and consistent.</p>
</li>
<li><p>HTML Beautifier: Elevate the aesthetics of your HTML code for better readability.</p>
</li>
<li><p>CSS Beautifier: Improve the structure and presentation of your CSS styles.</p>
</li>
<li><p>Base64 Encoder/Decoder: Encode and decode data with this versatile utility.</p>
</li>
<li><p>JWT Decoder: Decode JSON Web Tokens to inspect and verify their content.</p>
</li>
<li><p>Lorem Ipsum Generator: Generate placeholder text for content drafting and design prototyping.</p>
</li>
</ul>
<p>👉 <strong>Get Started</strong></p>
<p>Visit <a target="_blank" href="https://coderkit.dev"><strong>coderkit.dev</strong></a> and see how CoderKit can simplify your coding journey. Welcome to a world where coding just got a whole lot easier.</p>
<p>Here's to coding adventures with CoderKit! 🎉</p>
]]></content:encoded></item><item><title><![CDATA[Chat GPT explained by Chat GPT]]></title><description><![CDATA[GPT, or Generative Pre-training Transformer, is a type of language model developed by OpenAI that has been widely used for various natural language processing tasks. Language models are algorithms that are trained to predict the next word in a sequen...]]></description><link>https://blog.bibekkakati.me/chat-gpt-explained-by-chat-gpt</link><guid isPermaLink="true">https://blog.bibekkakati.me/chat-gpt-explained-by-chat-gpt</guid><category><![CDATA[chatgpt]]></category><category><![CDATA[openai]]></category><category><![CDATA[AI]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sat, 07 Jan 2023 14:50:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673102836078/5a0bf8cc-6db0-481d-a74b-3bff40602196.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>GPT, or Generative Pre-training Transformer, is a type of language model developed by OpenAI that has been widely used for various natural language processing tasks. Language models are algorithms that are trained to predict the next word in a sequence of text, based on the words that came before it. GPT takes this a step further by using an attention mechanism, which allows it to consider the entire input context when making predictions.</p>
<p>One of the main use cases for GPT is text generation. Given a prompt, GPT can generate human-like text that is coherent and flows naturally. This has a wide range of applications, including generating news articles, creating social media posts, and even writing code.</p>
<p>Another use case for GPT is language translation. By training GPT on a large dataset of parallel text in two different languages, it can learn the relationship between the languages and generate translations that are accurate and fluent.</p>
<p>GPT can also be used for summarization, by generating a shorter version of a long piece of text that retains the main points and ideas. This can be useful for creating summaries of news articles, research papers, and other lengthy documents.</p>
<p>One of the most notable use cases for GPT is chatbots. By training GPT on a large dataset of conversation transcripts, it can learn how to carry on a conversation with a user naturally and coherently. Chatbots powered by GPT has been used for customer service, providing information and assistance to users, and even for entertainment.</p>
<p>Aside from these specific use cases, GPT has also been used for a wide range of other natural language processing tasks, including question answering, text classification, and even creating music.</p>
<p>Overall, GPT is a powerful and versatile tool for natural language processing, with a wide range of use cases and applications. Its ability to generate human-like text and understand the context of a conversation makes it a valuable asset for a variety of industries and purposes.</p>
<p>Benefits or advantages of using chat GPT:</p>
<ul>
<li><p>Efficiency: Chatbots powered by GPT can handle a large volume of conversation without getting tired or needing breaks, which can be useful for customer service or other applications where there is a high demand for conversation.</p>
</li>
<li><p>Personalization: GPT can generate personalized responses based on the input it receives, allowing it to have unique conversations with different users.</p>
</li>
<li><p>Cost-effectiveness: Using chatbots powered by GPT can be more cost-effective than hiring human employees to handle conversation tasks.</p>
</li>
<li><p>24/7 availability: Chatbots powered by GPT can be available to chat with users around the clock, which can be convenient for users who need assistance outside of regular business hours.</p>
</li>
<li><p>Language support: GPT can be trained in multiple languages, allowing it to carry on conversations with users in different languages.</p>
</li>
</ul>
<p>Drawbacks or disadvantages of using chat GPT:</p>
<ul>
<li><p>Limited understanding of context: While GPT can generate text that flows naturally and considers the input it receives, it is ultimately limited in its understanding of context and may not be able to fully understand the nuances and subtleties of human conversation.</p>
</li>
<li><p>Lack of empathy: As a machine learning model, GPT cannot feel empathy or understand the emotions of others. This can make it difficult for it to fully engage in empathetic or emotional conversations.</p>
</li>
<li><p>Limited creativity: GPT is limited by the data it was trained on and the algorithms that power it, which means it may not be able to come up with creative or original responses to certain prompts.</p>
</li>
<li><p>Lack of accountability: As a machine, GPT cannot take responsibility for its actions or hold itself accountable in the same way a human would. This can be a concern in certain applications, such as customer service.</p>
</li>
<li><p>Dependence on data quality: The quality of the responses generated by GPT is largely dependent on the quality of the data it was trained on. If the training data is biased or contains errors, the responses generated by GPT may also be biased or inaccurate.</p>
</li>
</ul>
<p><em>~ This article was written by Chat GPT.</em></p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[System Color Theme Check In JavaScript]]></title><description><![CDATA[Few days back I was wondering how to know if the system theme is dark or light in web using JavaScript and I found a way to detect that.
In this article, I will share the implementation that I used to check the system theme.

We will use the method m...]]></description><link>https://blog.bibekkakati.me/system-color-theme-check-in-javascript</link><guid isPermaLink="true">https://blog.bibekkakati.me/system-color-theme-check-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[CSS]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[Design]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sat, 23 Jul 2022 02:31:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1658523650520/T-PtB_zJT.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Few days back I was wondering how to know if the system theme is dark or light in web using JavaScript and I found a way to detect that.</p>
<p>In this article, I will share the implementation that I used to check the system theme.</p>
<ul>
<li><p>We will use the method <code>matchMedia()</code> provided by the browser's window interface.</p>
</li>
<li><p><code>matchMedia</code> method expects a <code>mediaQueryString</code> as a parameter and it will return a <code>MediaQueryList</code> object.</p>
</li>
<li><p><code>MediaQueryList</code> object will have a property called <code>matches</code> of Boolean data type.</p>
</li>
</ul>
<h2 id="heading-code">Code</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.matchMedia(<span class="hljs-string">'(prefers-color-scheme: dark)'</span>).matches) {
    <span class="hljs-comment">// Dark Mode</span>
}
</code></pre>
<p><code>prefers-color-scheme</code> is a CSS media feature used to detect the system color theme.</p>
<p>We can also have a listener, if user changes the theme in-between.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>
   .matchMedia(<span class="hljs-string">"(prefers-color-scheme: dark)"</span>)
   .addEventListener(<span class="hljs-string">"change"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
       <span class="hljs-keyword">const</span> theme = event.matches ? <span class="hljs-string">"dark"</span> : <span class="hljs-string">"light"</span>;
   });
</code></pre>
<p>Let me know in the comments if you are aware of any other way to detect the system theme in web.</p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[How to store coordinates in MySQL]]></title><description><![CDATA[Many times we capture the geo-location of users and store in the database for different use cases.
I have seen that most of the developers use multiple fields to store the latitude and longitude separately like
Table_name(field1, field2, ..., latitud...]]></description><link>https://blog.bibekkakati.me/how-to-store-coordinates-in-mysql</link><guid isPermaLink="true">https://blog.bibekkakati.me/how-to-store-coordinates-in-mysql</guid><category><![CDATA[MySQL]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Mon, 25 Apr 2022 15:58:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1650901833548/lyL2XBI14.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Many times we <a target="_blank" href="https://blog.bibekkakati.me/track-users-location-on-your-website">capture the geo-location</a> of users and store in the database for different use cases.
I have seen that most of the developers use multiple fields to store the latitude and longitude separately like
<code>Table_name(field1, field2, ..., latitude, longitude)</code>.</p>
<p>In this short article we will see an alternative way of storing coordinates in MySQL database using the spatial data types like <code>POINT</code>.</p>
<h3 id="heading-create-a-table">Create a table</h3>
<ul>
<li>Let us create a table named <code>locations</code>.</li>
<li>Field <code>coordinates</code> of data type <code>POINT</code>.</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> locations (
      <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span>(<span class="hljs-number">11</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> AUTO_INCREMENT,
      coordinates POINT,
      PRIMARY <span class="hljs-keyword">KEY</span> (<span class="hljs-keyword">id</span>)
);
</code></pre>
<h3 id="heading-insertion-of-coordinates">Insertion of coordinates</h3>
<ul>
<li>To insert/update the field <code>coordinates</code>, we need to prepare a string like this
<code>'POINT(latitude longitude)'</code>.</li>
<li>Then we will use the in-built function called <code>ST_GeomFromText</code> to create a geometry in given SRID from <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/gis-wkt-functions.html">WKT specification</a>.</li>
<li>Pass the prepared string of points into <code>ST_GeomFromText</code> function.</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> 
     locations (coordinates) 
<span class="hljs-keyword">VALUES</span> 
     (ST_GeomFromText(<span class="hljs-string">'POINT(21.67890 91.54789)'</span>);
</code></pre>
<p>Table will store and display the data in the following way</p>
<pre><code><span class="hljs-attribute">id</span>        coordinates
<span class="hljs-attribute">1</span>         POINT(<span class="hljs-number">21</span>.<span class="hljs-number">67890</span> <span class="hljs-number">91</span>.<span class="hljs-number">54789</span>)
</code></pre><hr />
<p>Also, check <a target="_blank" href="https://blog.bibekkakati.me/track-users-location-on-your-website">this</a> out to know how to capture user's geo-location in web browser.</p>
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[What is CDN?]]></title><description><![CDATA[CDN stands for Content Delivery Network. 
A CDN is a system of multiple servers distributed geographically which works together to provide fast delivery of Internet content like HTML pages, javascript files, stylesheets, videos and images etc.

Why d...]]></description><link>https://blog.bibekkakati.me/what-is-cdn</link><guid isPermaLink="true">https://blog.bibekkakati.me/what-is-cdn</guid><category><![CDATA[CDN]]></category><category><![CDATA[caching]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[server]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Tue, 29 Jun 2021 19:49:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624994997308/04ff-GtL-.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>CDN stands for <strong>Content Delivery Network</strong>. </p>
<p>A CDN is a system of multiple servers distributed geographically which works together to provide fast delivery of Internet content like HTML pages, javascript files, stylesheets, videos and images etc.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624993553169/hhgFOiQbH.png" alt="Origin Server.png" /></p>
<h4 id="heading-why-do-we-need-cdn">Why do we need CDN?</h4>
<ul>
<li><p>It reduces latency, thus it improves the website load time. Since the contents are distributed globally, the distance between clients and the content also gets reduced, resulting in faster access to the content.</p>
</li>
<li><p>Minimize downtime and increases availability due to their distributed nature.</p>
</li>
<li><p>Improves website security by providing DDoS mitigation and using secured and updated  SSL/TLS certificates.</p>
</li>
<li><p>It also helps in reducing bandwidth consumption costs of the origin server.</p>
</li>
</ul>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Introducing SURL 🎊 Shorten your URL]]></title><description><![CDATA[We all are aware of different URL shortening services like bit.ly, TinyURL etc. I was thinking of building a similar application as it seems very simple but it is very challenging when you consider scalability and reliability. Finally, I got the oppo...]]></description><link>https://blog.bibekkakati.me/introducing-surl-shorten-your-url</link><guid isPermaLink="true">https://blog.bibekkakati.me/introducing-surl-shorten-your-url</guid><category><![CDATA[HarperDB Hackathon]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Mon, 21 Jun 2021 10:55:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624215990493/5UpJLVSGB.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We all are aware of different URL shortening services like bit.ly, TinyURL etc. I was thinking of building a similar application as it seems very simple but it is very challenging when you consider scalability and reliability. Finally, I got the opportunity to build the application because of <a target="_blank" href="https://hashnode.com/n/harperdbhackathon">#harperdbhackathon</a> and it is here.</p>
<h3 id="introducing-surl">Introducing SURL 🎊</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624213602609/MfpUrq6Tt.png" alt="s1.png" /></p>
<p>You can try it out here: <a target="_blank" href="https://surl.bibekkakati.me/h0Q0000">surl.bibekkakati.me</a></p>
<hr />
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-string">What</span> <span class="hljs-string">is</span> <span class="hljs-string">SURL</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Why</span> <span class="hljs-string">I</span> <span class="hljs-string">created</span> <span class="hljs-string">SURL</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">How</span> <span class="hljs-string">to</span> <span class="hljs-string">use</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Current</span> <span class="hljs-string">Features</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">System</span> <span class="hljs-string">Overview</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Project</span> <span class="hljs-string">Code</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Tech</span> <span class="hljs-string">Stack</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Upcoming</span> <span class="hljs-string">Features</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Challenges</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Live</span> <span class="hljs-string">Demo</span>
</code></pre>
<hr />
<h3 id="what-is-surl">What is SURL? 🔗</h3>
<p>It is a web-based URL shortening service where user can generate a shorter form of their long URL.</p>
<h3 id="why-i-created-surl">Why I created SURL? ✨</h3>
<p>The reason behind creating this service is that I have always been fascinated with the working, implementation and management of this kind of services because of its backend engineering, system design, scalability related complexities.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624212651248/aEkphoBtM.png" alt="s2.png" /></p>
<h3 id="how-to-use">How to use? 📙</h3>
<ul>
<li><p>Go to <a target="_blank" href="https://surl.bibekkakati.me/h0Q0000">surl.bibekkakati.me</a></p>
</li>
<li><p>Paste your long URL</p>
</li>
<li><p>Once a short URL is generated, it will be shown on the screen</p>
</li>
<li><p>Click it to copy to clipboard</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624218406936/TAOe7qwkv.png" alt="ss3.png" /></p>
<h3 id="current-features">Current Features 💡</h3>
<ul>
<li><p>Generate a short URL instantly.</p>
</li>
<li><p>Most important feature 😉 <code>dark</code> and <code>light</code> mode.</p>
</li>
<li><p>Check the total URL hits by going to the <code>/hits</code> path of your short URL.</p>
</li>
</ul>
<blockquote>
<p>If your short URL is <code>https://surl.bibekkakati.me/h0QuiOk</code>, then go to <code>https://surl.bibekkakati.me/h0QuiOk/hits</code>.</p>
</blockquote>
<h3 id="system-overview">System Overview 👀</h3>
<p>Two services are there:</p>
<ul>
<li><p><code>SURL service</code> is the main client-facing service, which is responsible for serving static files and issuing a short URL against a provided long URL by the user with the help of an API. The service is built by keeping scalability in mind so we can deploy multiple instances of this service without any issue to balance the incoming request load.</p>
</li>
<li><p><code>KeyGen service</code>  is a standalone service that is responsible for generating unique keys for all the active <code>SURL service</code>. It generates 100,000 unique keys on request from any <code>SURL service</code> and returns the keys in response. Both the service communicate using gRPC.</p>
</li>
</ul>
<blockquote>
<p>Caching is used for faster access and to reduce the load on the database.</p>
</blockquote>
<h3 id="project-code">Project Code 👨‍💻</h3>
<ul>
<li><p>SURL service: https://github.com/bibekkakati/surl</p>
</li>
<li><p>KeyGen service: https://github.com/bibekkakati/surl-key-generator</p>
</li>
</ul>
<h3 id="tech-stack">Tech Stack 💻</h3>
<ul>
<li><p>Node.js (Express.js) - Backend framework</p>
</li>
<li><p>HarperDB - Database</p>
</li>
<li><p>Nginx - Proxy Server</p>
</li>
<li><p>Azure Cloud - Deployment</p>
</li>
</ul>
<h3 id="upcoming-features">Upcoming Features 🔮</h3>
<ul>
<li><p>User authentication</p>
</li>
<li><p>Dashboard</p>
</li>
<li><p>Custom short URL.</p>
</li>
<li><p>Analytics like unique visits, visitor's country, city etc.</p>
</li>
<li><p>QR-Code for short URL</p>
</li>
<li><p>Private URL i.e, a visitor needs permission to access it or an access code.</p>
</li>
</ul>
<h3 id="challenges">Challenges</h3>
<ul>
<li><p>Building a reliable and fast system.</p>
</li>
<li><p>Tuning the server to handle larger concurrent users. Still trying to get a better result.</p>
</li>
<li><p>Generating unique keys (short URL), which I achieved with the counter based approach.</p>
</li>
</ul>
<blockquote>
<p>KeyGen service assures that the same key will not be generated more than once.</p>
</blockquote>
<h3 id="live-demo">Live Demo 👇</h3>
<p><a target="_blank" href="https://surl.bibekkakati.me/h0Q0000">https://surl.bibekkakati.me</a></p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript  (Golang Style)]]></title><description><![CDATA[In this short article, we are going to see how we can handle error in JavaScript in Golang style.
I am assuming, you have some experience with JavaScript and you are aware of the issues with error handling like throwing an exception to the parent met...]]></description><link>https://blog.bibekkakati.me/error-handling-in-javascript-like-golang</link><guid isPermaLink="true">https://blog.bibekkakati.me/error-handling-in-javascript-like-golang</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[error handling]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Fri, 18 Jun 2021 18:52:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624042184684/ZCwxpXeal.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this short article, we are going to see how we can handle error in JavaScript in Golang style.</p>
<p>I am assuming, you have some experience with JavaScript and you are aware of the issues with error handling like throwing an exception to the parent method from try-catch block or chaining multiple then-blocks and implementing logic inside it. These things can easily mess up with the code making it difficult to read.</p>
<p>Golang avoids these type of problems by handling errors/exceptions atomically.</p>
<h4 id="error-handling-in-golang">Error handling in Golang</h4>
<pre><code class="lang-golang">result, err := methodCall()
<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
  <span class="hljs-comment">// handle error</span>
}
<span class="hljs-comment">// do something with the result</span>
</code></pre>
<p>We can use a similar pattern in JavaScript with the help of a <code>try-catch</code> block like this.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> methodCall();
    <span class="hljs-keyword">return</span> [result, <span class="hljs-literal">null</span>];
  } <span class="hljs-keyword">catch</span>(error) {
    <span class="hljs-keyword">return</span> [<span class="hljs-literal">null</span>, error];
  }
}
</code></pre>
<p>If any error occurs, we are returning the <code>error</code> in the second position of the array and the <code>result</code> as <em>null</em> in the first position.</p>
<p>If there is no error, we are returning the <code>result</code> in the first position and <code>error</code> as <em>null</em> in the second position.</p>
<p>Now we can call the <code>getData</code> method then handle the <code>result</code> and <code>error</code> like this.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [result, error] = <span class="hljs-keyword">await</span> getData();
<span class="hljs-keyword">if</span> (error !== <span class="hljs-literal">null</span>) {
  <span class="hljs-comment">// handle the error</span>
}
<span class="hljs-comment">// do something with the result</span>
</code></pre>
<p>This pattern of error handling makes it very easy to read and understand the code.</p>
<p>Let me know what do you think about this pattern.</p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Implement Copy to Clipboard on a Website]]></title><description><![CDATA[In this article, we are going to see how we can implement a copy to clipboard functionality on our website. On clicking the Copy button, the content/text of a paragraph tag should be copied to the clipboard which we can paste anywhere in our system.
...]]></description><link>https://blog.bibekkakati.me/how-to-implement-copy-to-clipboard-on-a-website</link><guid isPermaLink="true">https://blog.bibekkakati.me/how-to-implement-copy-to-clipboard-on-a-website</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[Angular]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sat, 12 Jun 2021 12:24:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1623498631223/1Wzbku6fd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we are going to see how we can implement a copy to clipboard functionality on our website. On clicking the <code>Copy</code> button, the content/text of a paragraph tag should be copied to the clipboard which we can paste anywhere in our system.</p>
<p>Let's directly jump onto the code part.</p>
<p>I am assuming you have some basic knowledge of HTML, JavaScript and DOM manipulation.</p>
<h3 id="code">👨‍💻 Code</h3>
<p>We will write a very simple HTML code to display the paragraph content and a copy button.</p>
<p><code>index.html</code></p>
<pre><code class="lang-HTML"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Copy To Clipboard<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"content"</span>&gt;</span>The text to be copied.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"copy"</span>&gt;</span>Copy Text<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><code>script.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Reference of the paragraph tag</span>
<span class="hljs-keyword">const</span> content = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"content"</span>);

<span class="hljs-comment">// Reference of the copy button</span>
<span class="hljs-keyword">const</span> copyBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"copy"</span>);

<span class="hljs-comment">// Copy button's onclick handler</span>
copyBtn.onclick = copyToClipboard;

<span class="hljs-comment">// Method responsible for copying the content</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">copyToClipboard</span>(<span class="hljs-params"></span>) </span>{
    navigator.clipboard
        .writeText(content.innerText)
        .then(<span class="hljs-function">() =&gt;</span> alert(<span class="hljs-string">"Copied to clipboard"</span>))
        .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> alert(e.message));
}
</code></pre>
<p>So first we are getting the reference of the <code>paragraph</code> tag and the <code>copy</code> button, then assigned the <code>onclick</code> handler to the <code>copy</code> button.</p>
<p>On clicking the <code>copy</code> button, the <code>copyToClipboard</code> method will get invoked.</p>
<h4 id="copy-to-clipboard">Copy To Clipboard</h4>
<p>Inside the <code>copyToClipboard</code> method we are using the Clipboard API.</p>
<blockquote>
<p>The Clipboard API can be used to implement cut, copy, and paste features within a web application.</p>
</blockquote>
<ul>
<li><p>The system clipboard is exposed through the global <code>navigator.clipboard</code> property.</p>
</li>
<li><p>The <code>writeText</code> method of the clipboard object expects a string value as an argument, which will be written to the clipboard.</p>
</li>
<li><p>It returns a promise which is resolved once the clipboard's contents have been updated. The promise is rejected in case of any kind of error.</p>
</li>
</ul>
<pre><code class="lang-javascript">...
navigator.clipboard
    .writeText(content.innerText)
    .then(<span class="hljs-function">() =&gt;</span> alert(<span class="hljs-string">"Copied to clipboard"</span>))
    .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> alert(e.message));
...
</code></pre>
<p>So we are passing the <code>inner text</code> of the paragraph tag to the <code>writeText</code> method and if the promise is resolved i.e, the text has been copied.</p>
<h3 id="bonus">✨ Bonus</h3>
<p>Similarly, we can implement <code>cut</code> functionality.</p>
<p>After the text has been copied to the clipboard, just overwrite the inner text of the paragraph tag with an empty string.</p>
<pre><code class="lang-javascript">navigator.clipboard
    .writeText(content.innerText)
    .then(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-comment">// Overwriting with an empty string</span>
        content.innerText = <span class="hljs-string">""</span>;
        alert(<span class="hljs-string">"Copied to clipboard"</span>);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> alert(e.message));
</code></pre>
<h3 id="demo">🔗 Demo</h3>
<p>Github Repo: <a target="_blank" href="https://github.com/bibekkakati/blogs-projects/tree/main/web/clipboard-api">Link</a></p>
<p>Try It Out: <a target="_blank" href="https://bibekkakati.github.io/blogs-projects/web/clipboard-api/">Link</a></p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Generate PDF of HTML Element in Browser]]></title><description><![CDATA[Hello everyone👋
In this article, we are going to see how we can generate a PDF of any HTML element in the browser i.e, entirely client-side.
We will use the package html2pdf to generate the PDF.
html2pdf is using html2canvas to convert the HTML elem...]]></description><link>https://blog.bibekkakati.me/generate-pdf-of-html-element-in-browser</link><guid isPermaLink="true">https://blog.bibekkakati.me/generate-pdf-of-html-element-in-browser</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[pdf]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Fri, 04 Jun 2021 20:11:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622837052556/TcOf2bamx.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone👋</p>
<p>In this article, we are going to see how we can generate a PDF of any HTML element in the browser i.e, entirely client-side.</p>
<p>We will use the package <a target="_blank" href="https://ekoopmans.github.io/html2pdf.js/"><code>html2pdf</code></a> to generate the PDF.</p>
<p><code>html2pdf</code> is using <code>html2canvas</code> to convert the HTML element to canvas and then into an image. Then it generates the PDF of the image with the help of <code>jsPDF</code>.</p>
<blockquote>
<p>If you want to know more about <code>html2canvas</code>, check out <a target="_blank" href="https://blog.bibekkakati.me/take-screenshot-of-html-element-using-javascript">this</a> article.</p>
</blockquote>
<h3 id="implementation">Implementation</h3>
<p>Let us see a small implementation of the package <code>html2pdf</code>.</p>
<h4 id="indexhtml">index.html</h4>
<p>A basic HTML page, where the package's bundle link is included.</p>
<p>Created a div block of simple content and a export PDF button. We will be generating a PDF of the div whose id is <code>view</code> on clicking the export PDF button.</p>
<pre><code class="lang-HTML"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>HTML2PDF<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://raw.githack.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">onload</span>=<span class="hljs-string">"main()"</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"view"</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Export PDF<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Using HTML2PDF<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"export-pdf"</span>&gt;</span>Export PDF<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="scriptjs">script.js</h4>
<p>JavaScript file containing the main method which will be invoked once the site loads and listening for the <code>onclick</code> event on the export PDF button.</p>
<p>On clicking the export PDF button, the <code>html2pdf</code> method will be called which takes the reference to the element (div) as its argument.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> view = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"view"</span>);
    <span class="hljs-keyword">var</span> exportPDF = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"export-pdf"</span>);
    exportPDF.onclick = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> html2pdf(view);
}
</code></pre>
<p>After clicking the button, the PDF will be generated and downloaded directly to your system.</p>
<p>We can also pass some configuration options in the <code>html2pdf</code> method to handle image type, quality, filename etc. To know more about it, check <a target="_blank" href="https://ekoopmans.github.io/html2pdf.js/">here</a>.</p>
<blockquote>
<p>Note: Image-based PDF's are non-searchable.</p>
</blockquote>
<hr />
<p>Github repo: <a target="_blank" href="https://github.com/bibekkakati/blogs-projects/tree/main/web/pdf-generator">PDF-Generator</a></p>
<p>Try it out: <a target="_blank" href="https://bibekkakati.github.io/blogs-projects/web/pdf-generator/">Live</a></p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Short Polling vs Long Polling]]></title><description><![CDATA[Hello everyone👋
Before proceeding, I am assuming, you are aware of the request-response architecture of a basic web application. To build a real-time application like a chat application we can't use the basic request-response architecture, but we ca...]]></description><link>https://blog.bibekkakati.me/short-polling-vs-long-polling</link><guid isPermaLink="true">https://blog.bibekkakati.me/short-polling-vs-long-polling</guid><category><![CDATA[communication]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[realtime]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Fri, 28 May 2021 14:15:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622211087485/BO8QX86k1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone👋</p>
<p>Before proceeding, I am assuming, you are aware of the request-response architecture of a basic web application. To build a real-time application like a chat application we can't use the basic request-response architecture, but we can use it with a <code>polling</code> mechanism to achieve the real-time behaviour. Apart from the polling mechanism we also have <code>SSE(server-side event)</code> and <code>WebSocket</code> to achieve real-time behaviour.</p>
<p>In this article, I am going to discuss two types of polling techniques i.e, <code>long polling</code> and <code>short polling</code>.</p>
<p>First, we need to know, what is <code>polling</code>?</p>
<h3 id="polling">Polling</h3>
<p>Polling is a technique in which the client sends a request to the server asking for data in an interval of time.</p>
<blockquote>
<p>The response from the server can be empty or any kind of data.</p>
</blockquote>
<h3 id="short-polling">Short Polling</h3>
<p><code>Short Polling</code> is a technique in which the client sends a request to the server asking for data at fixed delays after getting a response from the previously sent request.</p>
<ul>
<li><strong>Client</strong> sends a request to the <strong>Server</strong>.</li>
<li><strong>Server</strong> responds with an empty response or data, if available.</li>
<li><strong>Client</strong> will wait for the specified delay after receiving the response and continues the same request-response process again.</li>
</ul>
<p>This technique is very simple and doesn't consume server resources, but event notifications are not so instant and there will be some delay.</p>
<h4 id="example">Example</h4>
<p>A client sends a request to the server asking for data, but the data is not available at that time and the server responds with an empty response.</p>
<p>The client will wait for 5 seconds before sending the next request. That means if, in that interval of time (5 seconds), any data is available the client will not be notified about this. </p>
<p>The client will be able to get the data when it sends the next request.</p>
<p>So this technique is not so instant, and there will some delay.</p>
<h3 id="long-polling">Long Polling</h3>
<p><code>Long Polling</code> is a technique in which the client sends a request to the server asking for data, but the server doesn't respond instantly if no data is available, rather it waits for a specific amount of time. If in that interval of time, any event happens or data become available, the server will respond with that data and in case of no events or data, the server will respond with an empty response after the specified timeout.</p>
<p>This technique is more complex and does consume server resources, but it can notify the client without any delay so it can give a better real-time experience.</p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[NanoID - Alternative To UUID]]></title><description><![CDATA[Hey coders 👋
If you are a JavaScript developer, I am pretty much sure that you have used the npm package UUID at least once in your development journey.

For those who don't know what is UUID. It is an npm package to generate a unique string ID. Sim...]]></description><link>https://blog.bibekkakati.me/nanoid-alternative-to-uuid</link><guid isPermaLink="true">https://blog.bibekkakati.me/nanoid-alternative-to-uuid</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sun, 23 May 2021 15:53:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621784796338/3UyibLZuF.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey coders 👋</p>
<p>If you are a JavaScript developer, I am pretty much sure that you have used the npm package <a target="_blank" href="https://www.npmjs.com/package/uuid"><code>UUID</code></a> at least once in your development journey.</p>
<blockquote>
<p>For those who don't know what is <code>UUID</code>. It is an npm package to generate a unique string ID. Similar packages are available in other languages too.</p>
</blockquote>
<p>But in this article I am not going to discuss <code>UUID</code>, rather I will discuss another awesome npm package to generate a unique ID known as <a target="_blank" href="https://www.npmjs.com/package/nanoid"><code>NanoID</code></a>.</p>
<h3 id="what-is-nanoid">What is NanoID?</h3>
<p>A tiny, secure, URL-friendly, unique string ID generator for JavaScript.</p>
<h3 id="why-nanoid">Why NanoID?</h3>
<ul>
<li>It is smaller in size as it has no dependencies.</li>
<li>It is 60% faster than UUID.</li>
<li>It uses cryptographically strong random APIs.</li>
<li>It uses a larger alphabet than UUID (A-Za-z0-9_-).</li>
</ul>
<blockquote>
<p>We can control the behaviour of alphabets to be used.</p>
</blockquote>
<p>NanoID is available in almost all the most used <a target="_blank" href="https://www.npmjs.com/package/nanoid#other-programming-languages">programming languages</a>.</p>
<p><code>Disclaimer: All the above claims are picked from the package's docs itself. 😉</code></p>
<h3 id="implementation">Implementation</h3>
<p>It is very easy to implement. Will write the code in a Node.js environment using CommonJS import.</p>
<h4 id="basic-way">Basic Way</h4>
<p>It will generate the ID synchronously.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing</span>
<span class="hljs-keyword">const</span> { nanoid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nanoid"</span>);

<span class="hljs-comment">// It will generate and return an ID with 21 characters</span>
<span class="hljs-keyword">const</span> id = nanoid();
</code></pre>
<h4 id="async-way">Async way</h4>
<p>It will generate the ID asynchronously.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing async API</span>
<span class="hljs-keyword">const</span> { nanoid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nanoid/async"</span>);

<span class="hljs-comment">// It will generate and return an ID with 21 characters</span>
<span class="hljs-keyword">const</span> id = <span class="hljs-keyword">await</span> nanoid();
</code></pre>
<h4 id="custom-size">Custom Size</h4>
<p>You can also pass the required ID's size as an argument.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing</span>
<span class="hljs-keyword">const</span> { nanoid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nanoid"</span>);

<span class="hljs-comment">// It will generate and return an ID with 10 characters</span>
<span class="hljs-keyword">const</span> id = nanoid(<span class="hljs-number">10</span>);
</code></pre>
<p>Reducing the size will increase the collisions probability.</p>
<h4 id="non-secure">Non-Secure</h4>
<p>If you want performance and not concerned with security, then you can use the non-secure way.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing non-secure API</span>
<span class="hljs-keyword">const</span> { nanoid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nanoid/non-secure"</span>);

<span class="hljs-keyword">const</span> id = nanoid();
</code></pre>
<h4 id="custom-character-or-size">Custom Character or Size</h4>
<p>You can control what characters you want to be included in your ID.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing customAlphabet API</span>
<span class="hljs-keyword">const</span> { customAlphabet } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nanoid"</span>);

<span class="hljs-comment">// First Param: Characters</span>
<span class="hljs-comment">// Second Param: ID size</span>
<span class="hljs-keyword">const</span> nanoid = customAlphabet(<span class="hljs-string">"123456789qwerty"</span>, <span class="hljs-number">8</span>);

<span class="hljs-comment">// Generated ID would be like: "q15y6e9r"</span>
<span class="hljs-keyword">const</span> id = nanoid();
</code></pre>
<p>You can also use the <code>customAlphabet</code> with <code>async way</code> and <code>non-secure way</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Importing async API</span>
<span class="hljs-keyword">const</span> { customAlphabet} = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nanoid/async"</span>);

<span class="hljs-comment">// Importing non-secure API</span>
<span class="hljs-keyword">const</span> { customAlphabet} = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nanoid/non-secure"</span>);
</code></pre>
<p>You can also check for the ID collision probability <a target="_blank" href="https://zelark.github.io/nano-id-cc/">here</a>.</p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Types Of Frontend Websites]]></title><description><![CDATA[Hello everyone👋
Technology has evolved in different ways and in the same way the concepts of building products or tools. Frontend web development is one of the domains which is changing rapidly with the growing community and requirements of faster d...]]></description><link>https://blog.bibekkakati.me/types-of-frontend-websites</link><guid isPermaLink="true">https://blog.bibekkakati.me/types-of-frontend-websites</guid><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[Angular]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sun, 16 May 2021 17:05:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621184119671/sViOiLJ97.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone👋</p>
<p>Technology has evolved in different ways and in the same way the concepts of building products or tools. Frontend web development is one of the domains which is changing rapidly with the growing community and requirements of faster development. Many libraries and frameworks have been introduced to the developers starting from jquery to react, angular etc. Every technology, concept, library and framework have its own pros and cons but they know how to stand out as per the requirement.</p>
<p>In this article, I am going to discuss different methods of creating frontend sites.</p>
<h3 id="topics">Topics</h3>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-string">Vanilla</span> <span class="hljs-string">HTML</span> <span class="hljs-string">Websites</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Client-Side</span> <span class="hljs-string">Rendering</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Server-Side</span> <span class="hljs-string">Rendering</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">Static-Site</span> <span class="hljs-string">Generator</span>
</code></pre>
<h3 id="vanilla-html-websites">Vanilla HTML Websites</h3>
<p>Vanilla HTML or Static Websites are the raw form of websites that we build using <code>HTML</code>, <code>CSS</code>, <code>JavaScript</code>. They are directly served from a web host or CDN.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621176481419/sVusuh4Lb.jpeg" alt="Static Website" /></p>
<h4 id="pros">Pros</h4>
<ul>
<li>It is easy to get started with.</li>
<li>Generally, not so complex.</li>
<li>SEO optimization can be done.</li>
</ul>
<h4 id="cons">Cons</h4>
<ul>
<li>Less modularity; Hard to update/maintain pages as we need to rewrite a lot of the same code for every page.</li>
<li>New request to the server for every page.</li>
<li>Generally, do not contain dynamic data.</li>
</ul>
<h3 id="client-side-rendering">Client-Side Rendering</h3>
<p>You may have heard this term many times, it is also known as CSR in short. So what happens in Client-Side Rendering?</p>
<p>When we build a site with React, Angular or Vue, it creates a SPA (Single Page Application) that doesn't have any pre-rendered <code>HTML</code> pages. When the browser requests the server for the site, the initial request is for a blank HTML page and then it fetches the JS scripts that manipulate the DOM and render the pages. Routing, data handling etc., are also done within the browser itself.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621177704707/CzL1inkZ7.png" alt="Client Side Rendering" /></p>
<h4 id="pros">Pros</h4>
<ul>
<li>Easy to maintain codebase.</li>
<li>Modular approach.</li>
<li>It's fast except for the initial request.</li>
</ul>
<h4 id="cons">Cons</h4>
<ul>
<li>It is not SEO friendly.</li>
<li>It can become complex.</li>
</ul>
<blockquote>
<p><code>React.js</code>, <code>Angular</code>, <code>Vue</code> can be used to build SPAs.</p>
</blockquote>
<p>We can optimize these kinds of sites with Server-Side Rendering.</p>
<h3 id="server-side-rendering">Server-Side Rendering</h3>
<p>In Server-Side Rendering, the pages are rendered on the server on every request for it. The server aggregates the data from its source like a database and fed it to the templates to render the requested HTML pages. And rendered pages are then sent back to the browser, to display to the user.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621178361766/o92jvSxda.png" alt="Server Side Rendering" /></p>
<h4 id="pros">Pros</h4>
<ul>
<li>Easy to maintain codebase.</li>
<li>Modular approach.</li>
<li>SEO friendly.</li>
</ul>
<h4 id="cons">Cons</h4>
<ul>
<li>Network latency can impact.</li>
<li>New request for every page.</li>
</ul>
<blockquote>
<p><code>Next.js</code> for React and <code>Nuxt.js</code> for Vue can be used for Server-Side Rendering.</p>
</blockquote>
<p>There is a hybrid approach to get benefits of both CSR and SSR which we will be discussing next.</p>
<h3 id="static-site-generator">Static-Site Generator</h3>
<p>In Static-Site Generator, the static pages are compiled at the build-time i.e, before deployment with some initial data. The static pages are then deployed to a web server. After the initial request, the site behaves more like a Single-Page Application.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621179375849/uDbKkaMo5.png" alt="Static Site Generator" /></p>
<h4 id="pros">Pros</h4>
<ul>
<li>Easy to maintain codebase.</li>
<li>Modular approach.</li>
<li>SEO friendly.</li>
</ul>
<h4 id="cons">Cons</h4>
<ul>
<li>It can become complex.</li>
</ul>
<blockquote>
<p><code>Gatsby.js</code> with React can be used for Static-Site Generator.</p>
</blockquote>
<h3 id="conclusion">Conclusion</h3>
<p>There is no hard and fast rule on which one you should use. It depends on your application and its usage.</p>
<p>In my opinion, Client-Side Rendering is suited for applications where users will stay for a longer time and will interact often and want a user experience similar to a desktop application. For example, a trading platform.</p>
<p>Server-Side Rendering is good for applications like <a class="user-mention" href="https://hashnode.com/@hashnode">Hashnode</a>, a blogging platform.</p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[True Is Not Always True In JavaScript]]></title><description><![CDATA[Hello everyone👋
In this article, I will try to explain the behaviour of the boolean data type of JavaScript.
We often use if statements in JavaScript to check if a value, that can be of any data type is true or false. But do you know that these valu...]]></description><link>https://blog.bibekkakati.me/true-is-not-always-true-in-javascript</link><guid isPermaLink="true">https://blog.bibekkakati.me/true-is-not-always-true-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Fri, 14 May 2021 18:02:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621015243341/2rNYLWjk3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone👋</p>
<p>In this article, I will try to explain the behaviour of the <code>boolean</code> data type of JavaScript.</p>
<p>We often use <code>if</code> statements in JavaScript to check if a value, that can be of any data type is <code>true</code> or <code>false</code>. But do you know that these values are not really <code>true</code> or <code>false</code>, rather they are considered as <code>truthy</code> or <code>falsy</code> values?</p>
<h3 id="explanation">Explanation</h3>
<p>Let's understand this with an example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> val = <span class="hljs-string">"blog"</span>;
<span class="hljs-keyword">if</span> (val) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span>);
}
</code></pre>
<p>So in the above code snippet, we declared a variable <code>val</code> which is storing a string <code>"blog"</code>.</p>
<p>In general, <code>if</code> statements expect a boolean expression or a boolean condition but here we are passing the variable <code>val</code> directly without any boolean expression.</p>
<p>And this <code>if</code> statement evaluates the value of <code>val</code> to <code>true</code> and execute its block. But why?</p>
<h3 id="why">Why</h3>
<p>In JavaScript, any non-zero number including the negative numbers and non-empty strings are termed as <code>truthy</code> values and the <code>truthy</code> values are translated to boolean <code>true</code> when evaluated in a Boolean context.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621016536792/Fvp6R5Rca.png" alt="truthyfalsy.png" /></p>
<p>So in our example, as the value of the variable <code>val</code> is a string with data i.e, not empty, it is considered as a <code>truthy</code> value which evaluates to <code>true</code> in the <code>if</code> statement condition.</p>
<p>And the values other than the <code>truthy</code> values are termed as <code>falsy</code> values.</p>
<p><code>falsy</code> values in JavaScript.</p>
<ul>
<li><code>false</code></li>
<li><code>null</code></li>
<li><code>undefined</code></li>
<li><code>0</code></li>
<li><code>NAN</code></li>
<li><code>''</code></li>
<li><code>""</code></li>
<li><code>0n</code></li>
<li><code>-0</code></li>
<li><code>`` </code></li>
<li><code>document.all</code></li>
</ul>
<h3 id="conversion">Conversion</h3>
<p>Convert the <code>truthy</code> and <code>falsy</code> values to boolean <code>true</code> or <code>false</code>.</p>
<p>You can pass the <code>truthy</code> or <code>falsy</code> value to the <code>Boolean()</code> and it will return <code>true</code> or <code>false</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> val = <span class="hljs-string">"blog"</span>;
<span class="hljs-keyword">if</span> (<span class="hljs-built_in">Boolean</span>(val)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span>);
}
</code></pre>
<p>Or you can use the following syntax to convert it to a pure boolean value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> val = <span class="hljs-string">"blog"</span>;
<span class="hljs-keyword">if</span> (!!val) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span>);
}
</code></pre>
<p>We know this <code>truthy</code> or <code>falsy</code> concept is not so impacting but it is always better to handle pure boolean values.</p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Capture Screen And Stream Like Zoom Using JavaScript]]></title><description><![CDATA[Hello everyone👋
In this article, we will see how applications like zoom use Screen Capture API provided by the browsers to capture your screen and stream it to the other end.
We will see a basic implementation of capturing the screen just to get an ...]]></description><link>https://blog.bibekkakati.me/capture-screen-and-stream-like-zoom-using-javascript</link><guid isPermaLink="true">https://blog.bibekkakati.me/capture-screen-and-stream-like-zoom-using-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[video]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Thu, 13 May 2021 14:26:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620915654412/7w1LJHmDZ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone👋</p>
<p>In this article, we will see how applications like zoom use <code>Screen Capture API</code> provided by the browsers to capture your screen and stream it to the other end.</p>
<p>We will see a basic implementation of capturing the screen just to get an idea.</p>
<h3 id="screen-capture-api">Screen Capture API</h3>
<p>The Screen Capture API let the user select a screen or portion of a screen (such as a window) to capture as a media stream. This stream can then be recorded or shared with others over the network.</p>
<h3 id="implementation">Implementation</h3>
<p>First, we will create a simple HTML web page to show the captured screen's stream and buttons to start and stop capturing.</p>
<p><code>Filename: index.html</code></p>
<pre><code class="lang-HTML"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width,initial-scale=1.0"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Screen Share<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Screen Capture<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"start"</span>&gt;</span>Start Sharing<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"stop"</span>&gt;</span>Stop Sharing<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"video"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"800"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"680"</span> <span class="hljs-attr">autoplay</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>I am assuming you have some basic knowledge of <code>HTML</code> and <code>CSS</code>.</p>
<p>Now we will create the JavaScript file where we will implement the main logic part.</p>
<p><code>Filename: script.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> video = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"video"</span>);
  <span class="hljs-keyword">const</span> start = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"start"</span>);
  <span class="hljs-keyword">const</span> stop = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"stop"</span>);

  <span class="hljs-keyword">var</span> displayMediaOptions = {
    <span class="hljs-attr">video</span>: {
      <span class="hljs-attr">cursor</span>: <span class="hljs-string">"always"</span>,
    },
    <span class="hljs-attr">audio</span>: <span class="hljs-literal">false</span>,
  };

  start.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    startSharing();
  };
  stop.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    stopSharing();
  };

  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">startSharing</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
      video.srcObject = <span class="hljs-keyword">await</span> navigator.mediaDevices.getDisplayMedia(
        displayMediaOptions
      );
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
      }
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stopSharing</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">let</span> tracks = video.srcObject.getTracks();
      tracks.forEach(<span class="hljs-function">(<span class="hljs-params">track</span>) =&gt;</span> track.stop());
      video.srcObject = <span class="hljs-literal">null</span>;
    }
}

main();
</code></pre>
<ul>
<li><p>At first, we are assigning the reference of the <code>video</code> element and <code>button</code> elements.</p>
</li>
<li><p>Listening on the <code>start</code> and <code>stop</code> button for an <code>onclick</code> event, which will invoke the <code>startSharing</code> and <code>stopSharing</code> method respectively.</p>
</li>
<li><p><code>displayMediaOptions</code> is a kind of config option which we are passing when capturing the stream. </p>
<ul>
<li><code>audio: false</code> as we are not capturing the audio.</li>
<li><code>video.cursor: always</code> means the cursor will always be visible on the stream.</li>
</ul>
</li>
</ul>
<blockquote>
<p>Check the official <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API">docs</a> for other options.</p>
</blockquote>
<h4 id="start-sharing-function">Start Sharing Function</h4>
<p>To start capturing video from the screen, we are using the <code>getDisplayMedia</code> method on the instance of <code>navigator.mediaDevices</code>.</p>
<p>The Promise returned by the <code>getDisplayMedia</code> method resolves to a media stream that streams the captured screen which we are setting into the <code>video.srcObject</code>.</p>
<h4 id="stop-sharing-function">Stop Sharing Function</h4>
<p>To stop capturing the screen, we are fetching the list of all the tracks using the <code>getTracks</code> method of <code>video.srcObject</code>. Then looping through the track list and calling its <code>stop</code> method. This will stop the stream.</p>
<p>After that, we are setting the <code>video.srcObject</code> to <code>null</code>.</p>
<h3 id="example">Example✨</h3>
<p>Github Repo: <a target="_blank" href="https://github.com/bibekkakati/blogs-projects/tree/main/web/screen-capture-share">Screen Capture</a></p>
<p>Try it out: <a target="_blank" href="https://bibekkakati.github.io/blogs-projects/web/screen-capture-share">Live</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620914800343/C7ubdIAY8.png" alt="image.png" /></p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Detect Internet Connection Status In Browser]]></title><description><![CDATA[Hello everyone 👋
In this article, we are going to learn how can we detect the internet connection state on our website.
This can be very useful to improve user experience by showing snack messages or pop-ups when the browser is not able to connect t...]]></description><link>https://blog.bibekkakati.me/detect-internet-connection-status-in-browser</link><guid isPermaLink="true">https://blog.bibekkakati.me/detect-internet-connection-status-in-browser</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Browsers]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Wed, 12 May 2021 13:03:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620827716266/XW9efn4zY.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone 👋</p>
<p>In this article, we are going to learn how can we detect the internet connection state on our website.</p>
<p>This can be very useful to improve user experience by showing snack messages or pop-ups when the browser is not able to connect to the internet.</p>
<h3 id="implementation">Implementation</h3>
<p>We can get the current state of the connection by using <code>window.navigator.onLine</code>, which will return a <code>boolean</code> value.</p>
<ul>
<li><code>true</code> if connected.</li>
<li><code>false</code> if not connected.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> online = <span class="hljs-built_in">window</span>.navigator.onLine;
<span class="hljs-keyword">if</span> (online) {
  <span class="hljs-comment">// Is connected to internet</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Not connected to internet</span>
}
</code></pre>
<blockquote>
<p>If the browser doesn't support <code>window.navigator.onLine</code> the above example will always come out as <code>false</code> or <code>undefined</code>.</p>
</blockquote>
<h4 id="connection-state-changes-listener">Connection State Changes Listener</h4>
<p>We can also detect the connection state by listening for network state change events i.e, <code>online</code> and <code>offline</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'offline'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-comment">// Network disconnected</span>
  }
);

<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'online'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-comment">// Network connected</span>
  }
);
</code></pre>
<p>It's very easy to implement but there are some side cases where it might give a false-positive result.</p>
<ul>
<li><p>The computer is connected to a mobile hotspot, but mobile internet is not working then also you can get an <code>online</code> status.</p>
</li>
<li><p>The computer is running a virtualization software that has virtual ethernet adapters that are always "connected".</p>
</li>
</ul>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Unlimited Email Address With Gmail Account]]></title><description><![CDATA[Hello everyone 👋
In this short article, I will discuss how can we get unlimited email addresses with a single Gmail account.
Some of you might be using this feature already but I got to know about this recently so I thought of sharing.
Many times we...]]></description><link>https://blog.bibekkakati.me/unlimited-email-address-with-gmail-account</link><guid isPermaLink="true">https://blog.bibekkakati.me/unlimited-email-address-with-gmail-account</guid><category><![CDATA[email]]></category><category><![CDATA[gmail]]></category><category><![CDATA[tricks]]></category><category><![CDATA[features]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Tue, 11 May 2021 15:30:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620746847203/j0ODz00Ue.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone 👋</p>
<p>In this short article, I will discuss how can we get unlimited email addresses with a single Gmail account.</p>
<p>Some of you might be using this feature already but I got to know about this recently so I thought of sharing.</p>
<p>Many times we create multiple email accounts to sign up on websites, to avail free services or for testing purpose. We have some services like temp-mail but those are accessible to the public so we can't use them for personal accounts.</p>
<p>If you have a Gmail account then you have access to <code>unlimited</code> email addresses using that one account.</p>
<h3 id="how">How</h3>
<p>Let say your Gmail address is <code>username@gmail.com</code>.</p>
<p>Then you can use your Gmail address like this too.</p>
<ul>
<li><code>username+1@gmail.com</code></li>
<li><code>username+string@gmail.com</code></li>
</ul>
<blockquote>
<p>Just add any random string or number followed by a <code>+</code> sign to your Gmail username.</p>
</blockquote>
<p>It will deliver all the emails of these Gmail addresses to your primary Gmail address, so no need to worry about handling multiple accounts and you can use your mail address on any website as they will treat it as a different mail address.</p>
<h3 id="use-case">Use Case</h3>
<p>Suppose you are creating a banking account, then you can use <code>username+bank@gmail.com</code>. Now you can filter your emails easily by using this Gmail address.</p>
<p>It is also useful to track down any compromised accounts and spammers.</p>
<p><em><code>Some websites do not accept this format of mail address or they just trim it down.</code></em></p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Take Screenshot Of HTML Element Using JavaScript]]></title><description><![CDATA[Hello everyone 👋
A few months back, I was working on a web-based project where a feature was required that is to take a screenshot of an HTML div in the browser and show it to the user. I was like, sorry this is not possible. Then I did some researc...]]></description><link>https://blog.bibekkakati.me/take-screenshot-of-html-element-using-javascript</link><guid isPermaLink="true">https://blog.bibekkakati.me/take-screenshot-of-html-element-using-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[HTML Canvas]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Mon, 10 May 2021 18:28:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620670812873/GBe_-pH2T.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone 👋</p>
<p>A few months back, I was working on a web-based project where a feature was required that is to take a screenshot of an HTML div in the browser and show it to the user. I was like, <em>sorry this is not possible</em>. Then I did some research and got to know about this library called <a target="_blank" href="https://html2canvas.hertzen.com/">html2canvas</a>.</p>
<p>So in this article, I will show how can we capture a screenshot of a web page or any element of it using <code>html2canvas</code>.</p>
<h3 id="implementation">Implementation</h3>
<ul>
<li>Download the javascript file: <a target="_blank" href="https://html2canvas.hertzen.com">html2canvas</a></li>
</ul>
<h3 id="code">Code</h3>
<p>Include the <code>html2canvas.min.js</code> file in your HTML file.</p>
<pre><code class="lang-HTML">...
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./html2canvas.min.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
...
</code></pre>
<p>Now we will use the <code>html2canvas</code> method to capture the screenshot of our web page or the HTML element.</p>
<pre><code class="lang-javascript">html2canvas(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"main"</span>), {
  <span class="hljs-attr">allowTaint</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">useCORS</span>: <span class="hljs-literal">true</span>,
})
.then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">canvas</span>) </span>{
  <span class="hljs-comment">// It will return a canvas element</span>
  <span class="hljs-keyword">let</span> image = canvas.toDataURL(<span class="hljs-string">"image/png"</span>, <span class="hljs-number">0.5</span>);
})
.catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-comment">// Handle errors</span>
  <span class="hljs-built_in">console</span>.log(e);
});
</code></pre>
<p>The <code>html2canvas</code> method takes two arguments</p>
<ul>
<li>first is the HTML element whose screenshot you want.</li>
<li>second is a configuration object.</li>
</ul>
<p>In the <code>configuration object</code>, we are using</p>
<ul>
<li><code>allowTaint</code> to allow cross-origin images to taint the canvas.</li>
<li><code>useCORS</code> to attempt to load images from a server using CORS.</li>
</ul>
<blockquote>
<p>You can find the available configuration options <a target="_blank" href="https://html2canvas.hertzen.com/configuration">here</a>.</p>
</blockquote>
<p>Then we are converting the returned <code>canvas</code> into a base64 image URL using the <code>toDataUrl</code> method which expects two arguments</p>
<ul>
<li><code>type</code> : image format.</li>
<li><code>encodingOptions</code> : number between 0 and 1 indicating the image quality.</li>
</ul>
<p>And that's it, we captured the screenshot of our HTML element.</p>
<h3 id="important">Important</h3>
<p>This library has some issues, some of them are mentioned in the <a target="_blank" href="https://github.com/niklasvh/html2canvas">docs</a>. I recommend going through it and understand it before using it in any production-based environment.</p>
<blockquote>
<p>If you are aware of other ways to achieve a similar kind of result, please feel free to share.</p>
</blockquote>
<h3 id="example">Example</h3>
<p>Check out the GitHub <a target="_blank" href="https://github.com/bibekkakati/blogs-projects/tree/main/web/html-screenshot">Repo</a>.</p>
<p>Try it out here: <a target="_blank" href="https://bibekkakati.github.io/blogs-projects/web/html-screenshot/">Live</a>.</p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Generate QR Code In Javascript]]></title><description><![CDATA[Hello everyone 👋, this is going to be a very short article where I will show how can we generate a QR Code for any content in JavaScript.
Obviously, I am not going to implement everything from scratch and why should one do that when we have a pletho...]]></description><link>https://blog.bibekkakati.me/generate-qr-code-in-javascript</link><guid isPermaLink="true">https://blog.bibekkakati.me/generate-qr-code-in-javascript</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Javascript library]]></category><dc:creator><![CDATA[Bibek Kakati]]></dc:creator><pubDate>Sun, 09 May 2021 18:29:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620585329941/MYiGisLs6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone 👋, this is going to be a very short article where I will show how can we generate a QR Code for any content in JavaScript.</p>
<p>Obviously, I am not going to implement everything from scratch and why should one do that when we have a plethora of useful libraries in JavaScript.</p>
<p>I came across this awesome lightweight library or you can say a simple script <a target="_blank" href="https://github.com/davidshimjs/qrcodejs">qrcodejs</a>. It is very easy to use and is reliable too.</p>
<h3 id="implementation">Implementation</h3>
<ul>
<li><p>Download this zip file: <a target="_blank" href="https://github.com/davidshimjs/qrcodejs/zipball/master">qrcodejs</a></p>
</li>
<li><p>Extract it.</p>
</li>
<li><p>Now you can use the <code>qrcode.js</code> and <code>qrcode.min.js</code> file in your project.</p>
</li>
</ul>
<h3 id="code">Code</h3>
<p>Include the <code>qrcode.js</code> file in your HTML file.</p>
<pre><code class="lang-HTML">...
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./qrcode.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
...
</code></pre>
<p>Give an <code>id</code> to the <code>div</code> where you want to show the generated QR Code. Here I have used <code>"qrcode"</code> as my <code>id</code>.</p>
<pre><code class="lang-HTML">...
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"qrcode"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
...
</code></pre>
<p>Now we will create an object from the <code>QRCode</code> function. Need to pass the <code>id</code> of the output <code>div</code> which is <code>"qrcode"</code> in this case.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> QR_CODE = <span class="hljs-keyword">new</span> QRCode(<span class="hljs-string">"qrcode"</span>, {
  <span class="hljs-attr">width</span>: <span class="hljs-number">220</span>,
  <span class="hljs-attr">height</span>: <span class="hljs-number">220</span>,
  <span class="hljs-attr">colorDark</span>: <span class="hljs-string">"#000000"</span>,
  <span class="hljs-attr">colorLight</span>: <span class="hljs-string">"#ffffff"</span>,
  <span class="hljs-attr">correctLevel</span>: QRCode.CorrectLevel.H,
});
</code></pre>
<blockquote>
<p><code>correctLevel</code>: <code>L</code> for low, <code>M</code> for medium, <code>H</code> for high.</p>
</blockquote>
<p>Generate QRCode by calling the <code>makeCode</code> method of the QRCode object, which expects the <code>data</code> as its argument.</p>
<pre><code class="lang-javascript">QR_CODE.makeCode(<span class="hljs-string">"https://buymeacoffee.com/bibekkakati"</span>);
</code></pre>
<blockquote>
<p>It will automatically insert the generated QRCode in the <code>div</code> whose <code>id</code> has been provided while creating the QRCode object.</p>
</blockquote>
<h3 id="example">Example✨</h3>
<p>Check out the GitHub <a target="_blank" href="https://github.com/bibekkakati/qr-gen">Repo</a>.</p>
<p>Try it out here: <a target="_blank" href="https://bibekkakati.github.io/qr-gen/">Live</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620586396838/PuSFQynUo.jpeg" alt="Demo Image" /></p>
<p><em>Screenshot is taken from Google Lens while scanning.</em></p>
<hr />
<p>Thank you for reading 🙏</p>
<p>If you enjoyed this article or found it helpful, give it a thumbs-up 👍</p>
<p>Feel free to connect 👋</p>
<p><a target="_blank" href="https://twitter.com/kakatibibek">Twitter</a> | <a target="_blank" href="https://instagram.com/bibekkakati">Instagram</a> | <a target="_blank" href="https://linkedin.com/in/bibekkakati">LinkedIn</a></p>
]]></content:encoded></item></channel></rss>