<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kvs Sankar Kumar on Medium]]></title>
        <description><![CDATA[Stories by Kvs Sankar Kumar on Medium]]></description>
        <link>https://medium.com/@kvs.sankar23?source=rss-e9995bec892c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7zwZokcVeHdp_TZyQ0fGaw.jpeg</url>
            <title>Stories by Kvs Sankar Kumar on Medium</title>
            <link>https://medium.com/@kvs.sankar23?source=rss-e9995bec892c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:52:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kvs.sankar23/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a RAG using OpenSearch as VectorDB and AWS Bedrock]]></title>
            <link>https://medium.com/@kvs.sankar23/building-a-rag-using-opensearch-as-vectordb-and-aws-bedrock-a6221dae7c57?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6221dae7c57</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[opensearch]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 10:13:41 GMT</pubDate>
            <atom:updated>2024-09-17T10:13:41.555Z</atom:updated>
            <content:encoded><![CDATA[<p>This article demonstrates how to use OpenSearch as vector db and AWS Bedrock embeddings to build a retrieval-augmented question-answering. We will walk through how to split the content into chunks, store them as vector embeddings in OpenSearch, and perform a search based on user queries to answer questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4B7k_Q4_i2eo8lD8" /></figure><h3>Pre-requisites</h3><h4>1. Packages to install:</h4><pre>&quot;langchain&quot;: &quot;^0.2.0&quot;,<br>&quot;@aws-sdk/client-bedrock-runtime&quot;: &quot;^3.588.0&quot;,<br>&quot;@langchain/community&quot;: &quot;^0.2.1&quot;,<br>&quot;@opensearch-project/opensearch&quot;: &quot;^2.8.0&quot;,</pre><blockquote>Do checkout the latest version of these packages, these are just for reference.</blockquote><h4>2. Setting Up the Environment</h4><pre>OPENSEARCH_URL=&lt;Your_OpenSearch_URL&gt;<br>AWS_ACCESS_KEY_ID=&lt;Your_AWS_Access_Key&gt;<br>AWS_SECRET_ACCESS_KEY=&lt;Your_AWS_Secret_Key&gt;<br>OPENSEARCH_INDEX=pdf_index</pre><h4>3. Importing Necessary Modules</h4><pre>import setEnv from &quot;../setupenv.js&quot;;<br>setEnv();<br><br>import { Client } from &quot;@opensearch-project/opensearch&quot;;  // OpenSearch Client<br>import { BedrockEmbeddings } from &quot;@langchain/community/embeddings/bedrock&quot;;  // Bedrock Embeddings<br>import { OpenSearchVectorStore } from &quot;@langchain/community/vectorstores/opensearch&quot;;  // Vector Store for OpenSearch<br>import { Document } from &quot;@langchain/core/documents&quot;;  // Document representation<br>import { createRetrievalChain } from &quot;langchain/chains/retrieval&quot;;  // Retrieval Chain for QA<br>import { createStuffDocumentsChain } from &quot;langchain/chains/combine_documents&quot;;  // Chain to combine documents for generation<br>import { RecursiveCharacterTextSplitter } from &quot;langchain/text_splitter&quot;;  // For splitting text into chunks<br>import { BedrockChat } from &quot;@langchain/community/chat_models/bedrock&quot;;  // Bedrock LLM for generating answers<br><br>import pdfParse from &quot;pdf-parse&quot;;  // For parsing PDF documents</pre><h4>Step 0: Initializing opensearch client and bedrock embeddings</h4><pre>import { Client } from &quot;@opensearch-project/opensearch&quot;;<br>import { BedrockEmbeddings } from &quot;@langchain/community/embeddings/bedrock&quot;;<br><br>//use dotenv<br>const client = new Client({<br>  nodes: [process.env.OPENSEARCH_URL],<br>});<br><br>const embeddings = new BedrockEmbeddings({<br>  region: &quot;us-east-1&quot;,<br>  credentials: {<br>    accessKeyId: process.env.CLIENT_AWS_ACCESS_KEY_ID,<br>    secretAccessKey: process.env.CLIENT_AWS_SECRET_ACCESS_KEY,<br>  },<br>  model: &quot;amazon.titan-embed-text-v1&quot;,  // Bedrock Embedding Model<br>});</pre><h4>Step 1: Creating Index Mappings in opensearch</h4><pre>async function createIndexWithMapping() {<br>  const indexName = process.env.OPENSEARCH_INDEX || &quot;documents&quot;;<br>  const { body: indexExists } = await client.indices.exists({<br>    index: indexName,<br>  });<br><br>  if (!indexExists) {<br>    await client.indices.create({<br>      index: indexName,<br>      body: {<br>        settings: {<br>          &quot;knn&quot;: true,<br>          &quot;knn.algo_param.ef_search&quot;: 100<br>        },<br>        mappings: {<br>          &quot;properties&quot;: {<br>            &quot;vector_field&quot;: {<br>              &quot;type&quot;: &quot;knn_vector&quot;,<br>              &quot;dimension&quot;: 1536,<br>              &quot;method&quot;: {<br>                &quot;name&quot;: &quot;hnsw&quot;,<br>                &quot;space_type&quot;: &quot;cosinesimil&quot;,<br>                &quot;engine&quot;: &quot;nmslib&quot;<br>              }<br>            }<br>          }<br>        }<br>      }<br>    });<br>    console.log(&quot;Index created with the appropriate mappings.&quot;);<br>  } else {<br>    console.log(&quot;Index already exists. Consider updating or deleting it if mappings are incorrect.&quot;);<br>  }<br>}</pre><h4>Step 2: Deleting documents based on metadata in opensearch</h4><pre>export async function deleteDocuments(id) {<br>  const query = {<br>    query: {<br>      bool: {<br>        must: [{ match: { &quot;metadata.id&quot;: id } }],<br>      },<br>    },<br>  };<br><br>  try {<br>    await client.deleteByQuery({<br>      index: process.env.OPENSEARCH_INDEX,<br>      body: query,<br>    });<br>  } catch (err) {<br>    console.log(err);<br>  }<br>}</pre><h4>Step 3: Creating Documents with metadata in opensearch</h4><p>We are using langchain module to injest data into opensearch using bedrock embeddings.</p><pre>export async function createDocuments(text, indexName, metainfo) {<br>  try {<br><br>    const { body: indexExists } = await client.indices.exists({<br>      index: indexName,<br>    });<br>    if (!indexExists) {<br>      createIndexWithMapping(indexName);<br>    }<br><br>    const textSplitter = new RecursiveCharacterTextSplitter({<br>      chunkSize: 1000,<br>      chunkOverlap: 100,<br>    });<br><br>    const docs = await textSplitter.splitDocuments([<br>      new Document({<br>        metadata: {<br>          ...metainfo,<br>          uploadTime: new Date().toISOString(),<br>        },<br>        pageContent: text,<br>      }),<br>    ]);<br><br>    //deleting exisiting docs with same id<br>    await deleteDocuments(metainfo.id);<br><br>    const res = await OpenSearchVectorStore.fromDocuments(docs, embeddings, {<br>      client,<br>      indexName,<br>      vectorFieldName: &quot;vector_field&quot;,<br>    });<br><br>    console.log(&quot;Documents created successfully!&quot;);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>}</pre><h4>Step 4: Query data from opensearch</h4><pre>const queryVDB = async (text:string, status:string) =&gt; {<br>  try {<br>    const vectorStore = new OpenSearchVectorStore(embeddings, {<br>      client,<br>      indexName: process.env.OPENSEARCH_INTENT_INDEX,<br>      vectorFieldName: &quot;vector_field&quot;,<br>    });<br><br>    const result = await vectorStore.similaritySearch(text, 2);<br>    //pass the results to llms or use langchain modules<br>    return result;<br>  }catch(e){<br>    console.log(e);<br>  }</pre><blockquote>Stay updated on the latest Gen AI articles and insights by following me. Thank-you.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6221dae7c57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query is the best thing that happened to React]]></title>
            <link>https://medium.com/@kvs.sankar23/react-query-is-the-best-thing-that-happened-to-react-abd92553e953?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/abd92553e953</guid>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 10:25:51 GMT</pubDate>
            <atom:updated>2023-08-13T10:25:51.947Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>React Query is a powerful data-fetching library, has emerged as a game-changer in React development. It simplifies data management, optimizing network requests, and enhancing caching strategies.</p><p>Link to the package — <a href="https://www.npmjs.com/package/@tanstack/react-query">https://www.npmjs.com/package/@tanstack/react-query</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lI9eJXsQJj80khkPOJTMXA.png" /></figure><blockquote>Is it worth shifting from Redux to react-query??? Lets find out!!!</blockquote><h4>How does it make a difference?</h4><ol><li><strong>Effortless Data Fetching:</strong></li></ol><ul><li>Without React Query: Manually handling async calls with fetch or axios.</li><li>With React Query: Use useQuery for auto-fetching, reducing code complexity.</li></ul><pre>// Without React Query<br>fetch(&#39;/api/data&#39;).then(response =&gt; response.json()).then(data =&gt; ...);<br><br>// With React Query<br>const { data } = useQuery(&#39;data&#39;, () =&gt; fetch(&#39;/api/data&#39;)<br>                      .then(response =&gt; response.json())<br>                  );</pre><p><strong>2. Automatic Caching:</strong></p><ul><li>Without React Query: Implement custom caching mechanisms.</li><li>With React Query: Caching is built-in and updates automatically.</li></ul><pre>// Without React Query<br>const cachedData = localStorage.getItem(&#39;cachedData&#39;);<br><br>// With React Query<br>const { data } = useQuery([&#39;items&#39;], fetchData, { enabled: isConnected });</pre><p><strong>3. Real-time Updates:</strong></p><ul><li>Without React Query: Complex setup using Web Sockets and manual state management.</li><li>With React Query: Seamless integration of real-time features.</li></ul><pre>// Without React Query<br>socket.on(&#39;dataUpdate&#39;, updatedData =&gt; ...);<br><br>// With React Query<br>const { data } = useQuery(&#39;data&#39;, fetchData);</pre><p><strong>4. Global State Management:</strong></p><ul><li>Without React Query: Combine Context or other state management libraries.</li><li>With React Query: Use hooks for data and global state.</li></ul><pre>// Without React Query<br>const { data, dispatch } = useContext(AppContext);<br><br>// With React Query<br>const { data, mutate } = useQuery([&#39;items&#39;], fetchData);</pre><p><strong>5. Network Request Optimization:</strong></p><ul><li>Without React Query: Manually manage network requests and debounce.</li><li>With React Query: Automatic query optimization</li></ul><pre>// Without React Query<br>const debouncedFetch = debounce(fetchData, 300);<br><br>// With React Query<br>const { data } = useQuery([&#39;items&#39;], fetchData, { <br>                                 refetchOnWindowFocus: false <br>                                 }<br>                  );</pre><p><strong>6. Server Pagination &amp; Infinite Loading:</strong></p><ul><li>Without React Query: Handle pagination manually with complex logic.</li><li>With React Query: Streamlined infinite loading and pagination.</li></ul><pre>// Without React Query<br>const loadMore = () =&gt; fetchMoreData(pageNumber);<br><br>// With React Query<br>const { data, fetchNextPage } = useInfiniteQuery([&#39;items&#39;], fetchPageData);</pre><p><strong>7. Error Handling &amp; Retrying:</strong></p><ul><li>Without React Query: Implement error handling and retry logic manually.</li><li>With React Query: Built-in error handling and retrying.</li></ul><pre>// Without React Query<br>fetch(&#39;/api/data&#39;).catch(error =&gt; retry(fetchData, 3, error));<br><br>// With React Query<br>const { data } = useQuery([&#39;items&#39;], fetchData, { retry: 3 });</pre><p><strong>8. Developer-Friendly DevTools:</strong></p><ul><li>Without React Query: Rely on browser developer tools for insights.</li><li>With React Query: Debug with dedicated React Query DevTools.</li></ul><p>To see in action, here is an example of implementing displaying of data with pagination using react query.</p><h4>Example:</h4><p>Let&#39;s assume you have a set of data with pagination and filters. On clicking tabs you change filter, you have a dropdown to select nunber of items to display, you have previous and next buttons.</p><p><strong>Implementing this using react-query:</strong></p><pre>const Component = () =&gt; {<br><br>  const [filterA, setFilterA] = React.useState&lt;boolean&gt;(false);<br>  const [page, setPage] = React.useState&lt;number&gt;(1);<br>  const [pageSize, setPageSize] = React.useState&lt;number&gt;(10);<br><br>  const GetData= async (filters) =&gt; {<br>   try {<br>    const filterString = filters<br>     ? &quot;?&quot; + filters.map((filter) =&gt; filter.key + &quot;=&quot; + filter.value).join(&quot;&amp;&quot;)<br>     : &quot;&quot;;<br>      const url = &quot;/api/data/&quot; + filterString;<br>      const res = await axios.get(url);<br>      return res.data;<br>    } catch (err) {<br>      throw err;<br>    }<br>  };<br><br>  const {<br>    data,<br>    status,<br>    error<br>  } = useQuery([&quot;data&quot;, filterA, page, pageSize], () =&gt;<br>    GetData([<br>      {<br>        key: &quot;filter_a&quot;,<br>        value: filterA,<br>      },<br>      {<br>        key: &quot;page&quot;,<br>        value: page,<br>      },<br>      {<br>        key: &quot;page_size&quot;,<br>        value: pageSize,<br>      },<br>    ])<br>  );<br><br>  return (<br>          &lt;Tabs&gt;<br>            &lt;TabList&gt;<br>              &lt;Tab<br>                onClick={() =&gt; {<br>                  setFilterA(false);<br>                  setPage(1);<br>                }}<br>              &gt;<br>                Tab 1<br>              &lt;/Tab&gt;<br>              &lt;Tab<br>                onClick={() =&gt; {<br>                  setFilterA(true);<br>                  setPage(1);<br>                }}<br>              &gt;<br>                Tab 2<br>              &lt;/Tab&gt;<br>              &lt;Flex&gt;<br>                &lt;Button<br>                  onClick={() =&gt; setPage(page - 1)}<br>                  disabled={page === 1}<br>                &gt;<br>                  Previous<br>                &lt;/Button&gt;<br>                &lt;Text&gt;<br>                  {page}<br>                &lt;/Text&gt;<br>                &lt;Button<br>                  onClick={() =&gt; setPage(page + 1)}<br>                  disabled={data?.next === null}<br>                &gt;<br>                  Next<br>                &lt;/Button&gt;<br>                &lt;Select<br>                  value={pageSize}<br>                  onChange={(e) =&gt; setPageSize(Number(e.target.value))}<br>                &gt;<br>                  &lt;option value={10}&gt;10&lt;/option&gt;<br>                  &lt;option value={20}&gt;20&lt;/option&gt;<br>                  &lt;option value={50}&gt;50&lt;/option&gt;<br>                &lt;/Select&gt;<br>              &lt;/Flex&gt;<br>            &lt;/TabList&gt;<br><br>            &lt;TabPanels&gt;<br>              &lt;TabPanel&gt;<br>                {status === &quot;loading&quot; ? (<br>                  &lt;ComponentLoader /&gt;<br>                ) : (<br>                  &lt;DataTable data={data.results} /&gt;<br>                )}<br>              &lt;/TabPanel&gt;<br>              &lt;TabPanel&gt;<br>                {status === &quot;loading&quot; ? (<br>                  &lt;ComponentLoader /&gt;<br>                ) : (<br>                  &lt;DataTable data={data.results} /&gt;<br>                )}<br>              &lt;/TabPanel&gt;<br>            &lt;/TabPanels&gt;<br>          &lt;/Tabs&gt;<br>  );<br>};<br><br>export default Component;</pre><h4>Note:</h4><blockquote>Like useEffect has dependencies array, u can treat the array in useQuery similarly, whenever any variable changes in the array, the API gets triggered again. The same info will be used to cache the data and remember the corresponding API for it.</blockquote><pre>useQuery([&quot;data&quot;, a, b, c], () =&gt; GetData(a,b,c))</pre><p>So here whenever the a, b, c variable changes it gets triggered again.</p><h3>Conclusion:</h3><p>Yes, it’s definitely worth it to shift from Redux to react-query. You would still need Redux if u want to communicate complex local data across the components.</p><h4>Such use case when you would need Redux:</h4><p>When u have multiple components, and you are toggling display of components on different button clicks in different components which doesn’t have same parents.</p><p>But you no longer need to store the API layer data using Redux, since everything gets handled by react-query.</p><p>A round of applause, dear readers, for reaching the end — if you enjoyed this article as much as a developer loves a well-commented code, give it a clap to brighten my day! 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd92553e953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different ways of reading files in AWS Lambda]]></title>
            <link>https://medium.com/@kvs.sankar23/different-ways-of-reading-files-in-aws-lambda-7375a3749ed?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7375a3749ed</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[file-reading]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[parquet]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 05:16:16 GMT</pubDate>
            <atom:updated>2023-06-16T05:16:16.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DcM_jpB0RCu2vLdB.png" /></figure><p>AWS Lambda is a powerful serverless computing service that allows you to run your code without provisioning or managing servers. When working with Lambda, it’s common to encounter scenarios where you need to read files from various sources, such as Amazon S3 or other storage systems.</p><p>In this article, we’ll explore different methods for reading files in AWS Lambda, including reading text files, CSV files, and Parquet files.</p><p><strong>The most common way the lambda read the files are on event bridge trigger or s3 trigger or just from a s3 location.</strong></p><h4>Example of an event bridge trigger on Put Object:</h4><pre>{<br>  &quot;version&quot;: &quot;0&quot;,<br>  &quot;id&quot;: &quot;12345678-1234-1234-1234-123456789012&quot;,<br>  &quot;detail-type&quot;: &quot;AWS API Call via CloudTrail&quot;,<br>  &quot;source&quot;: &quot;aws.s3&quot;,<br>  &quot;account&quot;: &quot;123456789012&quot;,<br>  &quot;time&quot;: &quot;2023-06-15T12:34:56Z&quot;,<br>  &quot;region&quot;: &quot;us-west-2&quot;,<br>  &quot;resources&quot;: [],<br>  &quot;detail&quot;: {<br>    &quot;eventVersion&quot;: &quot;1.08&quot;,<br>    &quot;eventTime&quot;: &quot;2023-06-15T12:34:56Z&quot;,<br>    &quot;eventSource&quot;: &quot;s3.amazonaws.com&quot;,<br>    &quot;eventName&quot;: &quot;PutObject&quot;,<br>    &quot;awsRegion&quot;: &quot;us-west-2&quot;,<br>    &quot;sourceIPAddress&quot;: &quot;192.0.2.0&quot;,<br>    &quot;userAgent&quot;: &quot;AWS SDK for Python&quot;,<br>    &quot;requestParameters&quot;: {<br>      &quot;bucketName&quot;: &quot;my-s3-bucket&quot;,<br>      &quot;key&quot;: &quot;path/to/my-file.csv&quot;<br>    },<br>    &quot;responseElements&quot;: {<br>      &quot;x-amz-request-id&quot;: &quot;ABC123DEF456&quot;,<br>      &quot;x-amz-id-2&quot;: &quot;a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z&quot;<br>    },<br>    &quot;s3&quot;: {<br>      &quot;s3SchemaVersion&quot;: &quot;1.0&quot;,<br>      &quot;configurationId&quot;: &quot;MyEventConfig&quot;,<br>      &quot;bucket&quot;: {<br>        &quot;name&quot;: &quot;my-s3-bucket&quot;,<br>        &quot;ownerIdentity&quot;: {<br>          &quot;principalId&quot;: &quot;A1B2C3D4E5F6G7H8I9J0&quot;<br>        },<br>        &quot;arn&quot;: &quot;arn:aws:s3:::my-s3-bucket&quot;<br>      },<br>      &quot;object&quot;: {<br>        &quot;key&quot;: &quot;path/to/my-file.csv&quot;,<br>        &quot;size&quot;: 1024,<br>        &quot;eTag&quot;: &quot;1234567890abcdef&quot;,<br>        &quot;versionId&quot;: &quot;1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z&quot;,<br>        &quot;sequencer&quot;: &quot;A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0U1V2W3X4Y5Z&quot;<br>      }<br>    },<br>    &quot;eventSource&quot;: &quot;s3.amazonaws.com&quot;<br>  }<br>}</pre><h4>Reading on text files:</h4><p><em>On S3 Trigger:</em></p><pre>import boto3<br><br>s3_client = boto3.client(&#39;s3&#39;)<br><br>def lambda_handler(event, context):<br>    # Get the bucket and object key from the S3 event<br>    bucket = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>    object_key = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br>    <br>    # Retrieve the file from S3<br>    response = s3_client.get_object(Bucket=bucket, Key=object_key)<br>    <br>    # Read the file contents as text<br>    file_contents = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>    <br>    # Process the file contents as needed<br>    # ...</pre><p><em>On Event Bridge:</em></p><pre>import boto3<br><br>s3_client = boto3.client(&#39;s3&#39;)<br><br>def lambda_handler(event, context):<br>    # Extract the S3 bucket and object key from the event<br>    bucket = event[&#39;detail&#39;][&#39;requestParameters&#39;][&#39;bucketName&#39;]<br>    object_key = event[&#39;detail&#39;][&#39;requestParameters&#39;][&#39;key&#39;]<br>    <br>    # Retrieve the file from S3<br>    response = s3_client.get_object(Bucket=bucket, Key=object_key)<br>    <br>    # Read the file contents as text<br>    file_contents = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>    <br>    # Process the file contents as needed<br>    # ...</pre><h4>Reading CSV files:</h4><pre>import boto3<br>import csv<br>s3_client = boto3.client(&#39;s3&#39;)<br>def lambda_handler(event, context):<br>    # Extract the S3 bucket and object key from the event<br>    bucket = event[&#39;detail&#39;][&#39;requestParameters&#39;][&#39;bucketName&#39;]<br>    object_key = event[&#39;detail&#39;][&#39;requestParameters&#39;][&#39;key&#39;]<br>    <br>    # Retrieve the file from S3<br>    response = s3_client.get_object(Bucket=bucket, Key=object_key)<br>    <br>    # Read the file contents as text<br>    file_contents = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>    <br>    # Parse the CSV data<br>    csv_data = csv.reader(file_contents.splitlines())<br>    <br>    # Iterate over each row in the CSV data<br>    for row in csv_data:<br>        # Access the values in each column of the row<br>        column1 = row[0]<br>        column2 = row[1]<br>        # ... process the data as needed</pre><h4>Reading Parquet files</h4><pre>import boto3<br>import pyarrow.parquet as pq<br>s3_client = boto3.client(&#39;s3&#39;)<br>def lambda_handler(event, context):<br>    # Get the bucket and object key from the S3 event<br>    bucket = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>    object_key = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br>    <br>    # Retrieve the Parquet file from S3<br>    response = s3_client.get_object(Bucket=bucket, Key=object_key)<br>    <br>    # Read the Parquet file using pyarrow<br>    parquet_file = response[&#39;Body&#39;].read()<br>    parquet_table = pq.read_table(parquet_file)<br>    <br>    # Access the Parquet table data<br>    # Example: Get a specific column<br>    column_data = parquet_table.column(&#39;column_name&#39;)<br>    <br>    # Process the Parquet data as needed<br>    # ...</pre><p>I hope this article provides you with a comprehensive understanding of different file reading methods in AWS Lambda and helps you leverage the full potential of serverless computing for your file processing needs.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7375a3749ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Apache Spark — Java in 5 minutes]]></title>
            <link>https://medium.com/@kvs.sankar23/setup-apache-spark-java-in-5-minutes-366bf99d4313?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/366bf99d4313</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 15:44:50 GMT</pubDate>
            <atom:updated>2023-02-11T15:44:50.217Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setup Apache Spark — Java in 5 minutes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4fNG-ocKKIAcLYF9QtVCA.png" /></figure><h3>Introduction</h3><p>Apache Spark is an open-source data processing framework for big data applications. It provides a simple and fast way to process large amounts of data in a distributed environment. In this article, i will show you how to set up Apache Spark in 5 minutes using Docker and IntelliJ.</p><h3>Prerequisites:</h3><ol><li>Docker installed</li><li>Intellij Installed</li></ol><h3>Configuration:</h3><p>We will be utilizing the <strong>Spark 3.3.0 framework, optimized for Hadoop 3.3, with the use of OpenJDK 8 </strong>as our JDK.</p><h4>1. Create a new project in Intellij:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKOfpmWF1WYuZV5rhJM_BA.png" /></figure><ol><li><strong>Name the project</strong>: Choose a meaningful and descriptive name for your project that accurately reflects its purpose.</li><li><strong>Select Java and Maven</strong>: When creating a new project in IntelliJ, select “Java” as the programming language and “Maven” as the build tool. Maven is a popular build tool for Java projects that provides a standard structure for your project, automates the build process, and manages dependencies.</li><li><strong>Download JDK 1.8 from IntelliJ itself</strong>: IntelliJ provides the option to download and install the Java Development Kit (JDK) required for your project. In this case, select JDK 1.8, which is a commonly used version of Java.</li><li><strong>Create the project</strong>: After specifying the project name, programming language, build tool, and JDK, click on the “Create” button to create the project. IntelliJ will generate the required files and directories for a basic Maven project, allowing you to get started with development right away.</li></ol><p><strong><em>Additional steps you may consider:</em></strong></p><ol><li><strong>Configure Maven:</strong> Before you start coding, make sure to configure Maven by specifying the project details in the “pom.xml” file, including the project name, version, and dependencies.</li><li><strong>Set up the development environment</strong>: Ensure that your development environment is set up correctly by verifying that the JDK and IntelliJ are installed and configured properly.</li></ol><h4><em>Once the project is created,</em></h4><p>1. Add the below dependency in pom.xml</p><pre>&lt;!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;<br>    &lt;artifactId&gt;spark-core_2.13&lt;/artifactId&gt;<br>    &lt;version&gt;3.3.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>2. Create this docker compose file in your root folder:<strong> (</strong><a href="https://github.com/big-data-europe/docker-spark"><strong>reference</strong></a><strong>)</strong></p><blockquote>NOTE: Create a /tmp/spark-events-local directory in root folder</blockquote><pre>version: &#39;3&#39;<br>services:<br>  spark-master:<br>    image: bde2020/spark-master:3.3.0-hadoop3.3<br>    container_name: spark-master<br>    ports:<br>      - &quot;8080:8080&quot;<br>      - &quot;7077:7077&quot;<br>    environment:<br>      - INIT_DAEMON_STEP=setup_spark<br>  spark-worker-1:<br>    image: bde2020/spark-worker:3.3.0-hadoop3.3<br>    container_name: spark-worker-1<br>    depends_on:<br>      - spark-master<br>    ports:<br>      - &quot;8081:8081&quot;<br>    environment:<br>      - &quot;SPARK_MASTER=spark://spark-master:7077&quot;<br>  spark-worker-2:<br>    image: bde2020/spark-worker:3.3.0-hadoop3.3<br>    container_name: spark-worker-2<br>    depends_on:<br>      - spark-master<br>    ports:<br>      - &quot;8082:8081&quot;<br>    environment:<br>      - &quot;SPARK_MASTER=spark://spark-master:7077&quot;<br>  spark-history-server:<br>      image: bde2020/spark-history-server:3.3.0-hadoop3.3<br>      container_name: spark-history-server<br>      depends_on:<br>        - spark-master<br>      ports:<br>        - &quot;18081:18081&quot;<br>      volumes:<br>        - /tmp/spark-events-local:/tmp/spark-events</pre><p>3. To test the working and setup of your application, you can paste the following code in your Main.java file, which counts the number of words in a text file:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        SparkConf conf = new SparkConf().setAppName(&quot;SparkTest&quot;).setMaster(&quot;local&quot;);<br>        JavaSparkContext sc = new JavaSparkContext(conf);<br>        JavaRDD&lt;String&gt; rdd = sc.textFile(&quot;src/main/resources/test.txt&quot;);<br>        long count = rdd.flatMap(line -&gt; Arrays.asList(line.split(&quot; &quot;)).iterator())<br>                .map(word -&gt; word.replaceAll(&quot;[^a-zA-Z]&quot;, &quot;&quot;).toLowerCase())<br>                .filter(word -&gt; !word.isEmpty())<br>                .count();<br>        System.out.println(count);<br>    }<br>}</pre><p>4. Run the docker compose file and then run the Main.java file</p><p><em>Congratulations! You have successfully set up a Apache Spark and tested it with a Java application.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366bf99d4313" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying MERN App in Vercel]]></title>
            <link>https://medium.com/@kvs.sankar23/deploying-mern-app-in-vercel-60acd033cb84?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/60acd033cb84</guid>
            <category><![CDATA[mern]]></category>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[deploy]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 09:15:03 GMT</pubDate>
            <atom:updated>2022-09-05T09:15:03.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rp0kOjQQk2ughbzn.jpg" /></figure><h4>There are few things we need to configure to deploy a MERN application in Vercel:</h4><ol><li>While creating vercel project, <strong>choose framework preset as other</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Nr-aH0I8-428hJJoK99G3Q.png" /></figure><p>2. Now <strong>declare static folders in express</strong> and endpoints to serve these static files, also <strong>initialize the CORS</strong></p><p><em>Example template for index.js:</em></p><pre>require(&quot;dotenv&quot;).config();</pre><pre>const path = require(&quot;path&quot;);<br>const express = require(&quot;express&quot;);<br>const app = express();<br>const mongoose = require(&quot;mongoose&quot;);<br><strong>var cors = require(&quot;cors&quot;);</strong><br>const { default: axios } = require(&quot;axios&quot;);</pre><pre>app.use(express.urlencoded({ limit: &quot;50mb&quot;, extended: true }));<br>app.use(express.json({ limit: &quot;50mb&quot; }));</pre><pre><strong>app.use(cors());<br>app.use((req, res, next) =&gt; {<br>  res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);<br>  res.header(<br>    &quot;Access-Control-Allow-Headers&quot;,<br>    &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization,auth-token&quot;<br>  );<br>  if (req.method === &quot;OPTIONS&quot;) {<br>    res.header(&quot;Access-Control-Allow-Methods&quot;, &quot;PUT, POST, PATCH, DELETE, GET&quot;);<br>    return res.status(200).json({});<br>  }<br>  next();<br>});</strong></pre><pre>const connect = mongoose<br>  .connect(process.env.MONGO_URI, {<br>    useUnifiedTopology: true,<br>    useNewUrlParser: true,<br>  })<br>  .then(() =&gt; console.log(&quot;Mondo db connected....&quot;))<br>  .catch((err) =&gt; console.log(err));</pre><pre>app.use(&quot;/api/org&quot;, require(&quot;./routes/org&quot;));</pre><pre><strong>app.use(express.static(path.join(__dirname, &quot;./build&quot;)));</strong></pre><pre><strong>app.get(&quot;*&quot;, (req, res) =&gt; {<br>  res.sendFile(path.resolve(__dirname, &quot;./build/index.html&quot;), function (err) {<br>    if (err) {<br>      res.status(500).send(err + &quot;asasas not wokring&quot;);<br>    }<br>  });<br>});</strong></pre><pre>const port = process.env.PORT || 5000;<br>app.listen(port, () =&gt; console.log(`Listening on port ${port}`));</pre><pre>module.exports = app;</pre><p>3. <strong>Remove build/dist or any other static folders from .gitignore</strong> and push it to your GitHub repository.</p><p>4. Finally, <strong>add vercel.json </strong>in root directory</p><pre>{<br>  &quot;builds&quot;: [<br>    {<br>      &quot;src&quot;: &quot;./index.js&quot;,<br>      &quot;use&quot;: &quot;<a href="http://twitter.com/vercel/node">@vercel/node</a>&quot;<br>    }<br>  ],<br>  &quot;routes&quot;: [{ &quot;src&quot;: &quot;/(.*)&quot;, &quot;dest&quot;: &quot;/&quot; }]<br>}</pre><p>5. Rest, everything is the same.</p><p>6. Now push the whole thing into your repo and deploy it in vercel.</p><blockquote>Don’t forget to add your environmental variables in vercel dashboard.</blockquote><p>If you encounter any issues, feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60acd033cb84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your first npm package in just 5 minutes]]></title>
            <link>https://medium.com/@kvs.sankar23/create-your-first-npm-package-in-just-5-minutes-bc8fb75e8578?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc8fb75e8578</guid>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 09:33:47 GMT</pubDate>
            <atom:updated>2022-04-13T09:33:47.674Z</atom:updated>
            <content:encoded><![CDATA[<p>Do it right for the first time itself!!</p><blockquote><em>A medium-api-npm package to read articles from medium and display it in your website and also post articles from your blog website to medium, which most bloggers for dream for</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7qOZ2nQqaW2J_dKFs10JQ.png" /></figure><h3>Create your npm account</h3><ol><li>Visit <a href="https://www.npmjs.com/signup">here </a>and create your npm account</li><li>Once done creating go to your command prompt and type</li></ol><pre>npm adduser</pre><p>3. Type your username and password and you are ready to start</p><h3>What are we going to build ?</h3><p>The script we are going to write always depends on what we actually are going to build.</p><p>For starters lets build a small yet significant npm package. People always want to display their medium article in their blog website and also post their articles from blog website to medium. Medium has made it possible through medium API. But they need to know to work with rest API which everyone doesn’t know. So let’s create a npm package which makes it simple.</p><h4>Let’s get started !!!</h4><ol><li>Create an empty git repository</li><li>clone it and open it in your favorite code editor</li></ol><h3>Initialize npm</h3><pre>npm init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Woi1Sd6UPAaDPPwcYgmscA.png" /><figcaption>Add keywords so that it increases the coverage</figcaption></figure><h3>Create the index.js the entry point of our package</h3><p>This is the place where we write the code available for the user</p><h3>Install the devDependencies needed</h3><p>In my npm we need only Axios which is just a dev dependency</p><pre>npm i -D axios</pre><h3>Let’s start to code</h3><p>We need to get the medium article from user, to do that we need the integration token from medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDkepXfrKezuIqL70KS6Rw.png" /><figcaption>Medium→settings→integration token</figcaption></figure><p>First we are going to write the config object and get the user id which is needed to retrieve the data from user’s medium</p><pre>async function getMediumArticles(options) {<br>  const config = {<br>    headers: {<br>      &quot;Host&quot;: &quot;api.medium.com&quot;,<br>      &quot;Content-type&quot;: &quot;application/json&quot;,<br>      &quot;Authorization&quot;: `Bearer ${options.auth}`,<br>      &quot;Accept&quot;: &quot;application/json&quot;,<br>      &quot;Accept-Charset&quot;: &quot;utf-8&quot;,<br>    },<br>  };<br>  await axios.get(&quot;<a href="https://api.medium.com/v1/me">https://api.medium.com/v1/me</a>&quot;, config).then((res) =&gt; {<br>    userData = res.data.data;<br>  });<br>  await axios<br>    .get(`<a href="https://api.medium.com/v1/users/$%7BuserData.id%7D/publications%60,config">https://api.medium.com/v1/users/${userData.id}/publications`,config</a>)<br>    .then((res) =&gt; {<br>        userPublications= res.data.data;<br>    });<br>  return {userData,userPublications};<br>};</pre><h3>Posting an article to medium</h3><p>To post from your blog website to medium also we need that auth token</p><pre>async function addPost(options){<br>  const config = {<br>    headers: {<br>      &quot;Host&quot;: &quot;api.medium.com&quot;,<br>      &quot;Content-type&quot;: &quot;application/json&quot;,<br>      &quot;Authorization&quot;: `Bearer ${options.auth}`,<br>      &quot;Accept&quot;: &quot;application/json&quot;,<br>      &quot;Accept-Charset&quot;: &quot;utf-8&quot;,<br>    },<br>  };<br>  await axios.get(&quot;<a href="https://api.medium.com/v1/me">https://api.medium.com/v1/me</a>&quot;, config).then((res) =&gt; {<br>    userData = res.data.data;<br>  });<br>  await axios.post(`<a href="https://api.medium.com/v1/users/$%7BuserData.id%7D/posts%60,%7B">https://api.medium.com/v1/users/${userData.id}/posts`,{</a><br>    title: options.title,<br>    contentFormat: &quot;html&quot;,<br>    content: options.html,<br>    canonicalUrl: options.canonicalUrl,<br>    tags: [options.tags],<br>    publishStatus: options.publishStatus<br>  },config).then((res)=&gt;console.log(res.data)).catch(err=&gt;console.log(err));</pre><pre>}</pre><h3>Final step</h3><p>We need to export the functions we have made so that users can access them</p><pre>module.exports={getMediumArticles,addPost}</pre><h3>Publishing your first npm</h3><p>Type this in your command prompt and your package will be available for npm users</p><pre>npm publish</pre><p>Checkout the medium npm package <a href="https://www.npmjs.com/package/medium-api-npm"><strong>here</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc8fb75e8578" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Server-Side Rendering]]></title>
            <link>https://medium.com/@kvs.sankar23/react-server-side-rendering-3f3163f06a88?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f3163f06a88</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 09:31:38 GMT</pubDate>
            <atom:updated>2022-04-13T09:31:38.818Z</atom:updated>
            <content:encoded><![CDATA[<p>Make your React app more awesome. 😎😎😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wZQw2rIi2rztwXl9Wby0Q.png" /></figure><h3>Why is this needed?</h3><p>JavaScript’s frameworks, like react, brings a first-class user experience and also very developer-friendly. Beginners often build a complete website using starter kits like create-react-app and don’t realize the major issue until they go live.</p><p>If you have built a big website with many components and go to view page source, you don’t see any of them in it 🤔🤔 Why??</p><h3>React Server-Side Rendering</h3><p>Make your React app more awesome. 😎😎😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wZQw2rIi2rztwXl9Wby0Q.png" /></figure><h3>Why is this needed?</h3><p>JavaScript’s frameworks, like react, brings a first-class user experience and also very developer-friendly. Beginners often build a complete website using starter kits like create-react-app and don’t realize the major issue until they go live.</p><p>If you have built a big website with many components and go to view page source, you don’t see any of them in it 🤔🤔 Why??</p><h3>React Server-Side Rendering</h3><p>Make your React app more awesome. 😎😎😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wZQw2rIi2rztwXl9Wby0Q.png" /></figure><h3>Why is this needed?</h3><p>JavaScript’s frameworks, like react, brings a first-class user experience and also very developer-friendly. Beginners often build a complete website using starter kits like create-react-app and don’t realize the major issue until they go live.</p><p>If you have built a big website with many components and go to view page source, you don’t see any of them in it 🤔🤔 Why??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*J4Hfhb-6S4Edpkz0VOMYOw.png" /></figure><p>You can only see an empty div#root, which is obvious because react works on virtual DOM. The content of your website is actually rendered on the client. This is a huge issue for search engine optimization. 😰</p><p>💡 This can be solved by rendering the DOM on the server-side and sending it as a string to the client.</p><p>Many frameworks have implemented this for you, and one can use them directly, like <strong>Gatsby</strong> and <strong>Nextjs</strong>. However, in this article, I will be explaining how to implement SSR from scratch.</p><p><em>Assuming that you’re using many routes, redux, different styled-components, etc., let’s code accordingly to work for all kinds of react apps.</em></p><h3>Create a server using express</h3><p>Create a server.js file in the root directory of your app</p><p><strong>Initialize an express app</strong></p><pre>const express = require(&quot;express&quot;);<br>const path = require(&quot;path&quot;);<br>const port = process.env.PORT || 8080;<br>const app = express();</pre><pre>app.use(express.static(path.resolve(__dirname, &quot;.&quot;, &quot;build&quot;)));</pre><pre>app.get(&quot;*&quot;, (req, res, next) =&gt; {<br>  res.send(&quot;hello world&quot;);<br>});</pre><pre>app.listen(port,()=&gt;{<br> console.log(`App started in port ${port}`);<br>});</pre><p>Let’s get back to this after a while…</p><h3>Changes to be done in created react app</h3><p>Some changes need to be done in App.js and index.js</p><ol><li>Many people initialize their redux store in index.js, which is correct. But this creates a problem when we render App.js on the server-side. The components will not be able to access the Redux store if not</li></ol><h3>src/App.js</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf2305dc784ea5b6ad85ff8617d2d494/href">https://medium.com/media/cf2305dc784ea5b6ad85ff8617d2d494/href</a></iframe><h3>src/index.js</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27752440a09c0a3a00722a950ce50bda/href">https://medium.com/media/27752440a09c0a3a00722a950ce50bda/href</a></iframe><p>Here we wrap the App component with BrowserRouter on the client-side, not in App.js, because we need to import it in server.js where StaticRouter will be wrapped.</p><p>And instead of react-render, we use react-hydrate. Because React documentation says</p><blockquote><strong><em>hydrate</em></strong><em>() is Same as </em><strong><em>render</em></strong><em>() , but is used to </em><strong><em>hydrate</em></strong><em> a container whose HTML contents were </em><strong><em>rendered</em></strong><em> by ReactDOMServer . </em><strong><em>React</em></strong><em> will attempt to attach event listeners to the existing markup. </em><strong><em>React</em></strong><em> expects that the </em><strong><em>rendered</em></strong><em> content is identical between the server and the client.</em></blockquote><p><strong>Basically, it means that it hydrates the dried string sent from the server by making event listeners and all back alive.</strong></p><p>2. App needs to be wrapped with two wrappers, BrowserRouter from ‘react-router-dom’ and StaticRouter from ‘react-router.’ This enables the routes to work client and server-side properly. For this, the client app should need to be wrapped in BrowserRouter, whereas server-side with StaticRouter.</p><blockquote><em>This doesn’t mean that we will be having two App.js files. Everything will be just cleared in a moment</em></blockquote><h3>server.js</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be76425a75c8ded49aa6caef8a91c65b/href">https://medium.com/media/be76425a75c8ded49aa6caef8a91c65b/href</a></iframe><p>After npm run build, we can find index.html in build folder with <em>&lt;div id=”root”&gt;&lt;/div&gt;</em> which we read using the fs module and fill it with <em>&lt;App/&gt;</em> rendered as a string, replace it, and send it. We normally wrap the App component with BrowserRouter, but we wrap it with StaticRouter, analogous and stateless on the server-side. It accepts two props: the location we get from req.url from express routes, and the other is context. This, we pass an empty object. Normally context is useful to store information regarding those routes and can be made available using StaticContext prop</p><h3>src/Notfound.js</h3><p>When a route is not found, render Notfound.js or any other component add this so that we can access the redirect URL and some information regarding it on the server-side</p><pre>import React from &#39;react&#39;; <br>export default ({ staticContext = {} }) =&gt; {  <br>staticContext.status = 404;  <br>return &lt;h1&gt;Oops, nothing here!&lt;/h1&gt;;<br>};</pre><p>Add this in the server route</p><pre>if (context.url) {<br>  return res.redirect(301, context.url);<br>}</pre><p>Now, if you run node server.js, you will get many errors 🤧</p><p>Since react is es6 syntax, browsers can’t render it since they use old normal JavaScript. Hence, we need babel and many presents to convert it back to older JavaScript. To do this, first, we need to add a webpack config. It needs many dev dependencies like style-loader for rendering CSS files, preset-react, stage-0 for asynchronous functions, and many more, depending on the stuff you have used. I am providing the code containing almost everything.</p><p><em>I will explain it in detail in my next article building a webpack from react app</em></p><h3>webpack.config.js</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6690392955177a7828180de540bfdc6/href">https://medium.com/media/e6690392955177a7828180de540bfdc6/href</a></iframe><h4>package.json (partial)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a25f86e81e2f915c7fd9637f87c0a132/href">https://medium.com/media/a25f86e81e2f915c7fd9637f87c0a132/href</a></iframe><p>Now we need to register babel and some preset and then call server.js. So create index.js in root directory</p><h3>index.js</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27752440a09c0a3a00722a950ce50bda/href">https://medium.com/media/27752440a09c0a3a00722a950ce50bda/href</a></iframe><p>Now add a new script in package.json</p><pre>&quot;ssr&quot;: &quot;node index.js&quot;</pre><p>That’s it…</p><blockquote><em>npm run build</em></blockquote><blockquote><em>npm run ssr</em></blockquote><p>Now you can run these commands and view the page source; you can find the whole code rendered. You can also view the network tab to find the first request done by the local host to render the app.</p><p><em>If your website contains many routes and components, then definitely you will find the difference and feel how smooth and fast your app becomes </em>🤩🤩🤩</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f3163f06a88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing React App]]></title>
            <link>https://medium.com/@kvs.sankar23/dockerizing-react-app-b03006d78860?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03006d78860</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 09:16:43 GMT</pubDate>
            <atom:updated>2022-04-13T09:20:44.711Z</atom:updated>
            <content:encoded><![CDATA[<p>Make your app more awesome. 😎😎😎</p><h3>Why docker?</h3><p>Docker is an open-source containerization platform. Docker enables developers to package applications into containers — standardized executable components that combine application source code with all the <strong>operating system</strong> (OS) libraries and dependencies required to run the code in any environment.</p><p>To make your react app ready for hosting, we must dockerize it.</p><h3>Dockerizing React App</h3><p>Make your app more awesome. 😎😎😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5gpXNz6kKlDo_Umt.png" /></figure><h3>Why docker?</h3><p>Docker is an open-source containerization platform. Docker enables developers to package applications into containers — standardized executable components that combine application source code with all the <strong>operating system</strong> (OS) libraries and dependencies required to run the code in any environment.</p><p>To make your react app ready for hosting, we must dockerize it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4da399b86da506e43e111c2571695c8/href">https://medium.com/media/e4da399b86da506e43e111c2571695c8/href</a></iframe><p>9. Expose port 80</p><p>10. To run nginx within the container without halting, we should use daemon off configuration directive described in <a href="http://wiki.nginx.org/CoreModule">official docs</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/224c9f67f1ba070b9c18863a8ca08531/href">https://medium.com/media/224c9f67f1ba070b9c18863a8ca08531/href</a></iframe><p>Finally, create a docker image from the docker file using the following commands:</p><pre>docker image build -t &lt;username&gt;/&lt;image-name&gt; .</pre><pre>docker push &lt;username&gt;/&lt;image-name&gt;</pre><p>To test it before pushing, use :</p><pre>docker container run -d -p 8080:80 &lt;username&gt;/&lt;image-name&gt;</pre><blockquote><em>I highly recommend to use </em><a href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint"><strong><em>eslint vs-code extension</em></strong></a><em> while developing because even if there is a simple error your page won’t show up and it will be very difficult to know if it’s a problem with dockerizing or application code.</em></blockquote><p>One can use docker-compose also for speeding up the testing and building. image simultaneously in a better way</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c6c74ce49b63141c1c8dc84fba8e1c/href">https://medium.com/media/12c6c74ce49b63141c1c8dc84fba8e1c/href</a></iframe><p>Create a <strong>docker-compose.yml </strong>file and run the following commands:</p><pre>docker-compose up</pre><p>If you have come this far, you definitely liked the article. <strong>Please do consider <em>applauding </em>the article and following me for more such articles.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03006d78860" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enable Web Push Notifications for your React app]]></title>
            <link>https://medium.com/@kvs.sankar23/enable-web-push-notifications-for-your-react-app-ea9a39b36d9f?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9a39b36d9f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-push-notifications]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 09:06:54 GMT</pubDate>
            <atom:updated>2022-04-13T09:06:54.956Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Firebase cloud messaging</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rMGumKz0r1UOGC_fApQYKQ.png" /></figure><h3>First convert your React app to pwa</h3><p>I have explained this in detail in my previous article <a href="https://medium.com/@KvsSankar/converting-a-react-app-to-a-pwa-in-just-5-minutes-e302890d297?source=friends_link&amp;sk=5998e0eadef1a780e723f9e0a041ca45">here</a></p><h3>Steps involved :</h3><ol><li>Create a Firebase project</li><li>Enable cloud messaging</li><li>Initialize Firebase in our React app</li><li>Enable cloud messaging</li></ol><blockquote><em>The way firebase cloud messaging works is, it creates tokens for every user which needs to be stored in database(mongo or firebase itself). Using an api provided by firebase we send notifications as json data to all the users or selected users</em></blockquote><h3>Create Firebase project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7fl4hpLFl59yT8FYKOiBw.png" /></figure><p>Click <a href="https://console.firebase.google.com/">here </a>to open Firebase console and login with your credentials</p><ol><li>Create a new project and select web app</li><li>Go to settings→project settings→general</li><li>Get the Firebase SDK snippet</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vGNNSP57V5PvAIfCfP3xA.png" /></figure><h3>Now initialize the Firebase app using sdk</h3><p>Go to index.html and paste the cdns shown in the code snippet below to initialize Firebase</p><pre>&lt;script src=&quot;https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js&quot;&gt;&lt;/script&gt;</pre><pre>&lt;script src=&quot;https://www.gstatic.com/firebasejs/7.15.1/firebase-messaging.js&quot;&gt;&lt;/script&gt;</pre><pre>var firebaseConfig = {<br>        apiKey: &quot;.............&quot;,<br>        authDomain: &quot;..............&quot;,<br>        databaseURL: &quot;<a href="https://ventor-7f759.firebaseio.com/">.</a>...........&quot;,<br>        projectId: &quot;..........&quot;,<br>        storageBucket: &quot;...........&quot;,<br>        messagingSenderId: &quot;............&quot;,<br>        appId: &quot;....................&quot;,<br>        measurementId: &quot;.........&quot;,<br>      };<br>      firebase.initializeApp(firebaseConfig);</pre><p>First we create a messaging object and get token from each user. For this we need a public vapid key which can be found on Firebase console</p><p><em>settings→cloud messaging→web configuration</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gg9Yax_vGbIS6nRimeoDiw.png" /></figure><p>create one if there is no key pair or else copy it and add it in the public vapid key in the code shown below</p><pre>function showToken(a) {<br>        console.log(a);<br>}<br>const messaging = firebase.messaging();<br>      <br>messaging.usePublicVapidKey(&quot;paste the key pair here&quot;);<br>      <br>messaging.requestPermission().then(() =&gt; {<br>        console.log(&quot;granted&quot;);<br>      });<br>      <br>messaging<br>        .getToken()<br>        .then((currentToken) =&gt; {<br>          if (currentToken) {<br>            console.log(currentToken);<br>          } else {<br>            // Show permission request.<br>            console.log(<br>              &quot;No Instance ID token available&quot;<br>            );<br>            // Show permission UI.<br>            updateUIForPushPermissionRequired();<br>            setTokenSentToServer(false);<br>          }<br>        })<br>        .catch((err) =&gt; {<br>          console.log(&quot;An error occurred while retrieving token. &quot;, err);<br>          showToken(&quot;Error retrieving Instance ID token. &quot;, err);<br>          //setTokenSentToServer(false);<br>        });</pre><p>In the function showToken add the token to the database of your choice instead of consoling it</p><h3>Create a new Notification object on onmessage event</h3><pre>messaging.onMessage((payload) =&gt; {</pre><pre>var obj = JSON.parse(payload.data.notification);</pre><pre>var notification = new Notification(obj.title, {</pre><pre>icon: obj.icon,</pre><pre>body: obj.body,</pre><pre>});</pre><pre>});</pre><h3>Now go to serviceWorker.js and display the notification</h3><ol><li>First import the scripts in sw.js also and initialize the Firebase app so that you can access Firebase in sw file</li><li>One additional thing you need to add in your Firebase sdk is messagingSenderId which you can find</li></ol><p><em>settings→cloud messaging→project credentials→sender id</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tl1qSiU1MaAw1nHHYnV2hA.png" /></figure><pre>importScripts(&quot;<a href="https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js">https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js</a>&quot;);<br>importScripts(<br>  &quot;<a href="https://www.gstatic.com/firebasejs/7.15.1/firebase-messaging.js">https://www.gstatic.com/firebasejs/7.15.1/firebase-messaging.js</a>&quot;<br>);</pre><pre>firebase.initializeApp({<br>        messagingSenderId: &quot;.........&quot;,<br>        apiKey: &quot;.............&quot;,<br>        authDomain: &quot;..............&quot;,<br>        databaseURL: &quot;<a href="https://ventor-7f759.firebaseio.com/">.</a>...........&quot;,<br>        projectId: &quot;..........&quot;,<br>        storageBucket: &quot;...........&quot;,<br>        messagingSenderId: &quot;............&quot;,<br>        appId: &quot;....................&quot;,<br>        measurementId: &quot;.........&quot;,<br>});</pre><pre>const messaging = firebase.messaging();</pre><pre>messaging.setBackgroundMessageHandler(function (payload) {<br>  console.log(<br>    &quot;[firebase-messaging-sw.js] Received background message &quot;,<br>    payload<br>  );<br>  var obj = JSON.parse(payload.data.notification);<br>  var ntitle = obj.title;<br>  var noptions = {<br>    body: obj.body,<br>    icon: obj.icon,<br>  };<br>  return self.registration.showNotification(ntitle, noptions);<br>});</pre><p>Yay !! Every thing is set now. You just need to go to Firebase</p><p><em>console→cloud messaging→send new message</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VE9CnYAG0pXUF3CtWpw-wA.png" /></figure><p>You need to get the fcm token from the database where you stored the tokens using the function showToken</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*Qyf3VSH2Yi7MnVbTmuj08Q.png" /></figure><h3>ON THE WHOLE</h3><p>index.html</p><pre>&lt;script src=&quot;<a href="https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js">https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js</a>&quot;&gt;&lt;/script&gt;</pre><pre>&lt;script src=&quot;<a href="https://www.gstatic.com/firebasejs/7.15.1/firebase-messaging.js">https://www.gstatic.com/firebasejs/7.15.1/firebase-messaging.js</a>&quot;&gt;&lt;/script&gt;<br>    &lt;script&gt;<br>      function showToken(a) {<br>        console.log(a);<br>      }<br>      var firebaseConfig = {<br>        apiKey: &quot;.............&quot;,<br>        authDomain: &quot;..............&quot;,<br>        databaseURL: &quot;<a href="https://ventor-7f759.firebaseio.com/">.</a>...........&quot;,<br>        projectId: &quot;..........&quot;,<br>        storageBucket: &quot;...........&quot;,<br>        messagingSenderId: &quot;............&quot;,<br>        appId: &quot;....................&quot;,<br>        measurementId: &quot;.........&quot;,<br>      };<br>      // Initialize Firebase<br>      firebase.initializeApp(firebaseConfig);</pre><pre>const messaging = firebase.messaging();<br>      messaging.usePublicVapidKey(<br>        &quot;..............&quot;<br>      );<br>      messaging.requestPermission().then(() =&gt; {<br>        console.log(&quot;granted&quot;);<br>      });<br>      messaging<br>        .getToken()<br>        .then((currentToken) =&gt; {<br>          if (currentToken) {<br>            console.log(currentToken);<br>          } else {<br>            // Show permission request.<br>            console.log(<br>              &quot;No Instance ID token available. Request permission to generate one.&quot;<br>            );<br>            // Show permission UI.<br>            updateUIForPushPermissionRequired();<br>            setTokenSentToServer(false);<br>          }<br>        })<br>        .catch((err) =&gt; {<br>          console.log(&quot;An error occurred while retrieving token. &quot;, err);<br>          showToken(&quot;Error retrieving Instance ID token. &quot;, err);<br>          //setTokenSentToServer(false);<br>        });</pre><pre>messaging.onMessage((payload) =&gt; {<br>        var obj = JSON.parse(payload.data.notification);<br>        var notification = new Notification(obj.title, {<br>          icon: obj.icon,<br>          body: obj.body,<br>        });<br>      });<br>    &lt;/script&gt;<br>    &lt;script&gt;<br>      // Your web app&#39;s Firebase configuration</pre><pre>if (&quot;serviceWorker&quot; in navigator) {<br>        window.addEventListener(&quot;load&quot;, () =&gt; {<br>          navigator.serviceWorker<br>            .register(&quot;./firebase-messaging-sw.js&quot;)<br>            .then((reg) =&gt; console.log(&quot;Success: &quot;, reg.scope))<br>            .catch((err) =&gt; console.log(err));<br>        });<br>      }<br>    &lt;/script&gt;</pre><h3>firebase-messaging-sw.js</h3><pre>const CACHE_NAME = &quot;version-1&quot;;<br>const urlsToCache = [&quot;index.html&quot;, &quot;offline.html&quot;];</pre><pre>const self = this;</pre><pre>//install a service worker<br>self.addEventListener(&quot;install&quot;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; {<br>      console.log(&quot;openend cache&quot;);<br>      return cache.addAll(urlsToCache);<br>    })<br>  );<br>});</pre><pre>//listen for request<br>self.addEventListener(&quot;fetch&quot;, (event) =&gt; {<br>  event.respondWith(<br>    caches.match(event.request).then(() =&gt; {<br>      return fetch(event.request).catch(() =&gt; caches.match(&quot;offline.html&quot;));<br>    })<br>  );<br>});</pre><pre>//activate the service worker<br>self.addEventListener(&quot;activate&quot;, (event) =&gt; {<br>  const cacheWhitelist = [];<br>  cacheWhitelist.push(CACHE_NAME);<br>  event.waitUntil(<br>    caches.keys().then((cacheNames) =&gt; {<br>      return Promise.all(<br>        cacheNames.map((cacheName) =&gt; {<br>          if (!cacheWhitelist.includes(cacheName))<br>            return caches.delete(cacheName);<br>        })<br>      );<br>    })<br>  );<br>});</pre><pre>importScripts(&quot;<a href="https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js">https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js</a>&quot;);<br>importScripts(<br>  &quot;<a href="https://www.gstatic.com/firebasejs/7.15.1/firebase-messaging.js">https://www.gstatic.com/firebasejs/7.15.1/firebase-messaging.js</a>&quot;<br>);</pre><pre>firebase.initializeApp({<br>        messagingSenderId: &quot;...........&quot;,<br>        apiKey: &quot;.............&quot;,<br>        authDomain: &quot;..............&quot;,<br>        databaseURL: &quot;<a href="https://ventor-7f759.firebaseio.com/">.</a>...........&quot;,<br>        projectId: &quot;..........&quot;,<br>        storageBucket: &quot;...........&quot;,<br>        messagingSenderId: &quot;............&quot;,<br>        appId: &quot;....................&quot;,<br>        measurementId: &quot;.........&quot;,<br>});</pre><pre>const messaging = firebase.messaging();</pre><pre>messaging.setBackgroundMessageHandler(function (payload) {<br>  console.log(<br>    &quot;[firebase-messaging-sw.js] Received background message &quot;,<br>    payload<br>  );<br>  var obj = JSON.parse(payload.data.notification);<br>  var ntitle = obj.title;<br>  var noptions = {<br>    body: obj.body,<br>    icon: obj.icon,<br>  };<br>  return self.registration.showNotification(ntitle, noptions);<br>});</pre><p>In my next article I will brief you how to send push notifications using fcm(Firebase cloud messaging) API in bulk rather than just using the GUI</p><p>Stay tuned 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9a39b36d9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting your React app to PWA in just 5 minutes]]></title>
            <link>https://medium.com/@kvs.sankar23/converting-your-react-app-to-pwa-in-just-5-minutes-f5a344105f49?source=rss-e9995bec892c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5a344105f49</guid>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[manifest]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Kvs Sankar Kumar]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 08:49:00 GMT</pubDate>
            <atom:updated>2022-04-13T08:49:00.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuqyHxSRGk7zhKlR3-iWpA.jpeg" /></figure><h3>What is a Progressive web app?</h3><p>Web applications can reach <em>anyone, anywhere, on any device</em> with a single codebase. Native applications, are known for being incredibly rich and reliable. Now PWA is the best of two worlds. Progressive Web Apps (PWA) are built and enhanced with modern APIs to deliver native-like capabilities, reliability, and install ability while reaching <em>anyone, anywhere, on any device</em> with a single codebase.</p><h3>Why PWA ?</h3><p>Converting a web app to PWA gives it the power of native app experience. Now what do we actually mean by native app experience …?</p><ol><li>Offline work mode</li><li>Enables Push notifications</li><li>Full responsiveness and browser compatibility</li><li>Self-updates</li><li>Connectivity independence</li></ol><h3>How to convert a web app to pwa ?</h3><p>It’s as simple as that. First we need to create manifest.json, which is just like a configuration file for your web app.</p><h3>manifest.json</h3><pre>{<br>  &quot;short_name&quot;: &quot;...&quot;,<br>  &quot;name&quot;: &quot;.....&quot;,<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;logo64.png&quot;,<br>      &quot;sizes&quot;: &quot;64x64 32x32 24x24 16x16&quot;,<br>      &quot;type&quot;: &quot;image/x-icon&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;logo192.png&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;logo512.png&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;sizes&quot;: &quot;512x512&quot;<br>    }<br>  ],<br>  &quot;start_url&quot;: &quot;.&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;theme_color&quot;: &quot;#17202a&quot;,<br>  &quot;background_color&quot;: &quot;#17202a&quot;<br>}</pre><p>Here theme color and background color are the color which appears as flash on opening the web app. The standalone display gives a native app look, it opens in full screen like an app. These are some the most important properties of manifest file.</p><p><em>The most important part of a pwa is a serviceWorker</em></p><h3>Now what is a serviceWorker !!</h3><blockquote><em>A </em><strong><em>service worker</em></strong><em> is a background </em><strong><em>worker</em></strong><em> that acts as a programmable proxy, allowing us to control what happens on a request-by-request basis.</em></blockquote><p>This basically means that a sw is a script (A <strong>JavaScript</strong> file) that runs in background and assists in offline first web application development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qpc8gHdUKlMwwWUVWWCWAQ.jpeg" /><figcaption>Basic structure of pwa</figcaption></figure><p>ServiceWorker is the intermediate between network and application. A sw need to be registered for a web application in order to function offline and enable push notifications. It converts the data into cache so that it need not reload the whole data on every visit. The offline mode is also enabled in such manner.</p><h3>Registering a serviceWorker</h3><p>Add this as a script tag in index.html and create a file serviceWorker.js</p><pre>&lt;script&gt;<br>if (&quot;serviceWorker&quot; in navigator) {<br>        window.addEventListener(&quot;load&quot;, () =&gt; {<br>          navigator.serviceWorker<br>            .register(&quot;./serviceWorker.js&quot;)<br>            .then((reg) =&gt; console.log(&quot;Success: &quot;, reg.scope))<br>            .catch((err) =&gt; console.log(err));<br>        });<br>      }<br>&lt;/script&gt;</pre><p>Here we are checking if the browser supports serviceworker and if yes we register a serviceWorker file onload. We can follow the same method for any type of application react, angular, basic HTML etc;</p><h3>serviceWorker.js</h3><p>We create a cache name and an array containing files to be added in cache. We are doing this so that it doesn’t reload the logos and stuff every time one visits a page. Service worker contains promises and all asynchronous stuff. This the reason why it looks overwhelming sometimes</p><h4>Installing a Serviceworker</h4><pre>const CACHE_NAME = &quot;version-1&quot;;<br>const urlsToCache = [&quot;index.html&quot;, &quot;offline.html&quot;];</pre><pre>const self = this;</pre><pre>self.addEventListener(&quot;install&quot;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; {<br>      console.log(&quot;openend cache&quot;);<br>      return cache.addAll(urlsToCache);<br>    })<br>  );<br>});</pre><h4>Listening for requests</h4><p>sw doesn’t have any direct connection with the contents of web app. It’s more like an API. So that we need to listen to requests coming from browser</p><pre>self.addEventListener(&quot;fetch&quot;, (event) =&gt; {<br>  event.respondWith(<br>    caches.match(event.request).then(() =&gt; {<br>      return fetch(event.request).catch(() =&gt; caches.match(&quot;offline.html&quot;));<br>    })<br>  );<br>});</pre><h4>Activate a service worker</h4><p>Every time the page reloads a new cache is created. Now the previous cache becomes useless. Hence, we need to delete the previous cache and keep the updated cache only. This can be done by adding the cache names to an array named whitelistedcache and check every time if the cache isn’t in whitelist then delete it.</p><pre>self.addEventListener(&quot;activate&quot;, (event) =&gt; {<br>  const cacheWhitelist = [];<br>  cacheWhitelist.push(CACHE_NAME);<br>  event.waitUntil(<br>    caches.keys().then((cacheNames) =&gt; {<br>      return Promise.all(<br>        cacheNames.map((cacheName) =&gt; {<br>          if (!cacheWhitelist.includes(cacheName))<br>            return caches.delete(cacheName);<br>        })<br>      );<br>    })<br>  );<br>});</pre><blockquote><em>It can be done in the same way for react or any other framework. Create-react-app includes service worker.js in src file. We can render it as script through index.js or else do it in the same way by creating serviceWorker.js in public folder.</em></blockquote><h3>ON THE WHOLE CONVERTING REACT TO PWA</h3><h4>index.html</h4><p>//main html file</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;link rel=&quot;icon&quot; href=&quot;%PUBLIC_URL%/logo64.png&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>    &lt;meta name=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt;<br>    &lt;meta<br>      name=&quot;description&quot;<br>      content=&quot;Web site created using create-react-app&quot;<br>    /&gt;<br>    &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;%PUBLIC_URL%/logo192.png&quot; /&gt;<br>    &lt;link rel=&quot;manifest&quot; href=&quot;%PUBLIC_URL%/manifest.json&quot; /&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    <br>    &lt;script&gt;<br>if (&quot;serviceWorker&quot; in navigator) {<br>        window.addEventListener(&quot;load&quot;, () =&gt; {<br>          navigator.serviceWorker<br>            .register(&quot;.serviceWorker.js.js&quot;)<br>            .then((reg) =&gt; console.log(&quot;Success: &quot;, reg.scope))<br>            .catch((err) =&gt; console.log(err));<br>        });<br>      }<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>serviceWorker.js (in public folder itself)</p><pre>const CACHE_NAME = &quot;version-1&quot;;<br>const urlsToCache = [&quot;index.html&quot;, &quot;offline.html&quot;];</pre><pre>const self = this;</pre><pre>//install a service worker<br>self.addEventListener(&quot;install&quot;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; {<br>      console.log(&quot;openend cache&quot;);<br>      return cache.addAll(urlsToCache);<br>    })<br>  );<br>});</pre><pre>//listen for request<br>self.addEventListener(&quot;fetch&quot;, (event) =&gt; {<br>  event.respondWith(<br>    caches.match(event.request).then(() =&gt; {<br>      return fetch(event.request).catch(() =&gt; caches.match(&quot;offline.html&quot;));<br>    })<br>  );<br>});</pre><pre>//activate the service worker<br>self.addEventListener(&quot;activate&quot;, (event) =&gt; {<br>  const cacheWhitelist = [];<br>  cacheWhitelist.push(CACHE_NAME);<br>  event.waitUntil(<br>    caches.keys().then((cacheNames) =&gt; {<br>      return Promise.all(<br>        cacheNames.map((cacheName) =&gt; {<br>          if (!cacheWhitelist.includes(cacheName))<br>            return caches.delete(cacheName);<br>        })<br>      );<br>    })<br>  );<br>});</pre><p>Thanks for your valuable time and hope you succeed in creating a progressive react app :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a344105f49" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>