<?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 Vipul Nema on Medium]]></title>
        <description><![CDATA[Stories by Vipul Nema on Medium]]></description>
        <link>https://medium.com/@vipulnema2610?source=rss-9f9fe01bf09f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WbCTMXu-CtiQyr59FqT_Kw.jpeg</url>
            <title>Stories by Vipul Nema on Medium</title>
            <link>https://medium.com/@vipulnema2610?source=rss-9f9fe01bf09f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:23:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vipulnema2610/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[Streamline Build Size with Yarn 3’s Focus Command]]></title>
            <link>https://medium.com/@vipulnema2610/streamline-build-size-with-yarn-3s-focus-command-967c5b3045c4?source=rss-9f9fe01bf09f------2</link>
            <guid isPermaLink="false">https://medium.com/p/967c5b3045c4</guid>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[yarn-workspace]]></category>
            <category><![CDATA[yarn-3]]></category>
            <category><![CDATA[build-size]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <dc:creator><![CDATA[Vipul Nema]]></dc:creator>
            <pubDate>Thu, 18 May 2023 18:47:37 GMT</pubDate>
            <atom:updated>2023-05-18T18:59:30.197Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong>: Efficient package management is crucial for optimizing build size in JavaScript projects. Yarn, a popular package manager, has introduced a groundbreaking feature in its version 3: the focus command. This powerful tool enables developers to significantly reduce build size by selectively installing only the dependencies required for a specific package or application. In this blog post, we will explore the capabilities of Yarn 3’s focus command and how it can help streamline your build process for leaner and faster deployments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*R0jopk9j5AeKK6gDfGWx-g.png" /></figure><h3><strong>Understanding the Need for Build Size Optimization</strong></h3><p>As JavaScript projects grow in complexity, managing dependencies becomes increasingly challenging. Including unnecessary dependencies can bloat the build size, resulting in longer load times and decreased performance. To address this issue, Yarn 3 introduces the focus command, which allows developers to selectively install only the essential dependencies required for a specific package or application.</p><p>Getting Started with Yarn 3’s Focus Command</p><p>To leverage the power of the focus command, ensure that you have Yarn 3 installed on your system. Once you have set up your project with Yarn workspaces, you can execute the following command either from root and from inside package . (PACKAGE_Name)</p><pre>//Dockerfile <br>...<br>yarn workspaces focus  --production [PACAKGE_NAME]<br>&amp;&amp; yarn cache clean --all   <br>&amp;&amp;  rm -rf /usr/local/share/.cache/yarn/v6 <br>...</pre><h3><strong>“yarn workspaces focus”</strong></h3><p>— This command will analyze the dependencies of the specified package and install only the necessary packages, excluding devDependencies and unused files. By default, focus install operates in a mode that is optimized for production deployments. For more details see Doc — <a href="https://yarnpkg.com/cli/workspaces/focus">https://yarnpkg.com/cli/workspaces/focus</a></p><h3>To upgrade from yarn 1 to yarn 3 follow Offical doc, but i am sharing some steps -</h3><ol><li>yarn set version berry/latest/stable</li><li>define .yarnrc.yml file instead yarnrc.</li></ol><pre>//.yarnrc.yml<br>enableGlobalCache: true // for old node is way only<br><br>nodeLinker: node-modules // IF USING Node js install method or existing yarn 1<br><br>plugins:<br>  - path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs<br>    spec: &quot;@yarnpkg/plugin-workspace-tools&quot;<br><br>yarnPath: .yarn/releases/yarn-3.5.0.cjs</pre><p>3. yarn install and commit changes. done</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>Other steps we took to decrease build size. But These are individual separate topic to cover .</strong></p><ol><li>First identify items most contributing in increasing build size by using docker exec , and sudo du commands in local system .</li><li>Optimise docker layers. like small base image, less dependency , multi-stage build, remove not required code ,</li><li>Only install production dependency</li><li>Break monolithic code base into micofront app.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=967c5b3045c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Experience with React-Native on Web]]></title>
            <link>https://medium.com/@vipulnema2610/my-experience-with-react-native-on-web-924966510394?source=rss-9f9fe01bf09f------2</link>
            <guid isPermaLink="false">https://medium.com/p/924966510394</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native-web]]></category>
            <category><![CDATA[cross-platform-mobile-app]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Vipul Nema]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 14:58:26 GMT</pubDate>
            <atom:updated>2023-02-10T14:58:26.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Last year, I got the opportunity to integrate<strong> react-native for existing web applications</strong>. Many people ask some common questions, So I thought that others may have similar queries too. I sharing my experience with React-Native for the web. These are my personal thoughts only.</p><p>First of all, Of course, cross-platform technology like React-Native and flutter is a very good idea for Apps, No doubt in that.</p><p><strong>But should we use it for the Web too?</strong> First It seems like common sense that React belongs to Web then why not use it here also? Practically we can use it on Web too but in my experience, it creates some challenges too and Web features are not simple to use.</p><p>There is one thing also the official doc is mainly about Apps(Andriod and IOS). Open community provided the supported package like react-native-web for other platforms like web and window. Day-by-day react-native community makes it more solid. Right now The main challenge is not about feasibility, it is about maintainability and scalability.</p><p>In my opinion, if you have below use cases then definitely you should use them or give them a try.</p><ol><li>Your organization sends frequent releases that want common product design and user experience for Mobile web and Apps.</li><li>Hurry to create an application for a new product/startup/prototype.</li><li>If you have on the web only with react application and now want App too then existing react resources can be utilized with fewer App experts.</li><li>Or Just want to try new technology for fun.</li></ol><p><strong>Main challenges I faced.</strong></p><ol><li>Complex application architecture to manage. like mono repo.</li><li>Frequent Build error fixing due to third-party packages.</li><li>Release process management like branch management and code guideline.</li><li>Engineer expertise — Integration in the existing web application may need good knowledge of concepts like — yarn workspace, lerna, sub-modules, webpack, babel etc.</li><li>Application Performance and SEO may need extra effort.</li><li>Developers and QA must verify the release for all platforms before releasing it on any platform. Their effort would increase in this process though development efforts would decrease.</li></ol><p><strong>How can we integrate on the web —</strong></p><p>If creating an application from scratch then the small enterprises can use <a href="https://docs.expo.dev/get-started/installation/">expo</a> boilerplate, but if you have more custom uses or you are a big organization then <a href="https://necolas.github.io/react-native-web/docs/setup/">custom setup</a>.</p><p><strong>Technical Challenges Faced —</strong></p><ol><li>Css-in-JS need to be used. I can’t use Css-modules. Both have self-props and cons.</li><li>Frequent build issues due to non-web-supported code or RN packages.</li><li>Server-side applications have extra challenges, like dimension API different values, and Css Extraction performance.</li><li>Direct images path can’t be imported we need to import CDN hoisted absolute path otherwise, App build size would increase.</li></ol><p><strong>Compare to Flutter- </strong><br> right I see trends people are picking flutter if they wanted App only for Andriod and IOS, but if want web app too they like RN. For debugging on the web, RN is easier than Flutter.</p><p>react-native-web maintainers did really a fantastic job, but still there are a lot of enhancement needed, We are supposing those in near future. But there is no doubt about cross platform development is today fronted skill either react-native or flutter. Apple, Google, facebook are also providing good support in that.</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=924966510394" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common Deployments for React Application for all Environments]]></title>
            <link>https://medium.com/@vipulnema2610/common-deployments-for-react-application-for-all-environments-b9486d6236f8?source=rss-9f9fe01bf09f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9486d6236f8</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[react-deployment]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[environment-variables]]></category>
            <dc:creator><![CDATA[Vipul Nema]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 10:47:27 GMT</pubDate>
            <atom:updated>2023-02-06T10:47:27.089Z</atom:updated>
            <content:encoded><![CDATA[<p>We are supposing you have this tech stack for React server-side applications. — React, Node Js, Webpack, Jenkins, Docker, k8.</p><p>Let&#39;s start.</p><blockquote>Normally for small application we create separate build using webpack . Define plugin helps in that. Team normally have Dev, Sanity, staging and production servers/environment. Your team may have other testing environment too like performance testing.</blockquote><p>But when you have a very big application then CI/CD time may also increase up to 15–20 mins. If after verification, if same changes have to deploy on all testing environments then the same waiting time would be faced by QA and Dev teams.</p><p><strong>The Solution is to Deploy a common build on all environments.</strong></p><p>Before going into details first let&#39;s understand why we build separately for all setups. The reason is environment code differences and on the client side, we don’t have this concept-” environment variables” like the backend. So using Define Plugin, We replace strings like “process.env.VAR” with some defined values. This is happening at build time and due to different values, we have to create different builds for different setups.</p><p><strong>So How can we Pass the environment variable at runtime? — <em>Passing process.env as a window property from the server-side HTML template- This solution may help existing applications using isomorphic code at the client and server sides.</em></strong></p><p><strong>Steps</strong> —</p><ol><li><strong>Create Common Docker build image</strong> — On Jenkins create a common image during the build. This takes 90% of the time, and we can save time by reusing it.</li><li><strong>Create Setup-wise docker build image</strong> — Then deploy on different setups and create an image using a previous common image as the base image. While this step we can copy .env_(environment) file into the .env file, Then while running the Node JS application it can read it. So this is how it would get setup-wise variable values.</li><li><strong>Access variables at server side </strong>- Because react server-side application can use env variables using <strong>process.env</strong> , we have to just disable DefinePlugin if we are using it for server build.</li><li><strong>Pass process.env Object to client-side</strong>- Enject env variable in HTML template for client-side after security filtering. Also, Do disable the Define plugin.</li><li><strong>Use At Client side</strong> — In webpack web build process.env is renamed like e.env so we have to use “node :{process:false}” in it’s config. We would also face publicPath issue that we can fix using <strong>__webpack_public_path__</strong></li></ol><pre>//index.js<br>__webpack_public_path__ = process.env.Public_Path;<br>import app.js<br><br>------------------------------------<br>//app.js<br>functio App ()=&gt;{<br>  return (<br>    &lt;div&gt; {process.env.API_URL}&lt;div&gt;<br>  )<br>}</pre><pre>//webpack.config.js<br>{<br>  entry,<br>  output,<br>  plugins :[<br>  ...plugins,<br>  // Remove or comment Define plugin<br>  //new DefinePlugins(envObjt)<br>  ],<br>  node:{<br>    process: false<br>  }<br>}</pre><pre>//index.hmtl<br>securedClientEnvs = filterClientEnv(process.env);<br><br>&lt;script&gt;<br>  let process= {};<br>  process.env = JSON.stringify(securedClientEnvs);<br>  window.process = env<br>&lt;script&gt;<br>&lt;body&gt;<br><br></pre><p>Note — Now if webpack5 and other not recommending to use process.env directly at client side. So for new application we can use some other names like _env.VAR and follow same steps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9486d6236f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Environment variable in react node webpack build]]></title>
            <link>https://medium.com/@vipulnema2610/environment-variable-in-react-node-webpack-build-b698774c7777?source=rss-9f9fe01bf09f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b698774c7777</guid>
            <dc:creator><![CDATA[Vipul Nema]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 05:05:58 GMT</pubDate>
            <atom:updated>2023-01-31T03:55:23.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>So before executing Node js script as an OS process, We can set/pass custom global <strong>execution context, </strong>“process” is a node JS global object like window.document on the client side. Using these we can make behave the same script differently.</h3><p>This <a href="http://Environment variable in react node webpack build  This concept was mainly used in backend application. But now a day frontend application are also utilising this in many important use cases.  So before executing Node js script as a OS process, We can set/pass custom execution context (using exoprt ENV_VAR or using .env file) using this concept. &quot;processe&quot; is a node JS global object like window.document at client side. Using these we can make behave same script differently. How to read environment variables from Node.js The process core module of Node.js provides the env property which hosts all the environment variables that were set at…nodejs.dev How to pass- Either directly using script arguments(export in unix) or reading from some file like .evn . How to use-  Using at Server side - We can access them using process.env. Normally in react node js applications. Build time Environment Variables are passed at Bundling time to create &quot;webpack webpack.config.js&quot; to create different bundle.server.js and bundle.client.js files. After that Runtime environment variable are passed at execution time to &quot;node bundle.server.js&quot;.  Using at Client side - Bundle.client.js can&#39;t use process.env directly because it executed at client side on browser platform so there is no process global object here. there are some way to make these utilise . Most famous way is using webpack DefinePlugin. Another way is to embed in HTML file in some window.process object  through server side controller. Second one is more complex and mainly used in creating Single build/image to deployment on different server platform(dev/stage/prod). First option is simple but only have disadvantage that we have to create different build every time we deploy on different environment servers. Use cases- now this we can think in different use cases like in webpack react build. Using different API names based on environments. Creating  different log path in local and production build Creating  different webpack public path domain for static files.  In monorepo deploy independently different pages/applications by using common build. We can create different path names for pages, using common configurable webpack logic.  Enabling/Disabling for utilities/plugins in webpack. etc…">concept</a> was mainly used in backend applications. But now a day frontend applications are also utilizing this in many important use cases.</p><p><strong>How to pass</strong>- Either directly using script arguments(export in Unix) or reading from some file like .env files.</p><p><strong>How to use-</strong></p><p><strong>Using on the Server side </strong>— We can access them using <strong>process.env. </strong>Normally in react node js applications. Build time Environment Variables are passed at Bundling time to create “webpack webpack.config.js” to create different bundle.server.js and bundle.client.js files. After that Runtime environment variables are passed at execution time to “node bundle.server.js”.</p><p><strong>Using on the Client side </strong>— Bundle.client.js can’t use process.env directly because it is executed at the client side on the browser platform so there is no global process object here. But there are some ways to make these utilize. The most famous way is using <a href="https://webpack.js.org/plugins/define-plugin/">webpack DefinePlugin</a>. Another way is to embed an HTML file in some window.process or window.env object through the server-side controller.</p><p>The second one is more complex and mainly used in creating<a href="https://blog.risingstack.com/create-react-app-runtime-env-cra/"> a Single build/image</a> for deployment on different server platforms (dev/stage/prod). The first option is simple but has a disadvantage: we have to create different builds every time we deploy on different environment servers.</p><p><strong>Use cases</strong>- We can use this in many cases which seems a very difficult problem to solve. There are some general use cases and some are specific to application and architecture.</p><p><strong>For a specific use</strong> case example- Suppose in the application, different pages are managed through yarn mono repo workspaces and also shared code present inside it. But we have to build and deploy each page separately using a common webpack build. Then we can define APP_NAME environment variable to generate different static file paths and deploy them on different server nodes.</p><p><strong>Other generate Use case examples </strong>—</p><ol><li>Defining different API URLs config based on environments.</li><li>Creating different log paths in local and production build.</li><li>Creating different webpack public paths for static files.</li><li>Enabling/Disabling for utilities/plugins at build time or runtime.</li><li>Enabling tracking on production and disabling on local development or testing environments.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b698774c7777" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration of web component in the application]]></title>
            <link>https://medium.com/@vipulnema2610/integration-of-web-component-in-the-application-95778877151b?source=rss-9f9fe01bf09f------2</link>
            <guid isPermaLink="false">https://medium.com/p/95778877151b</guid>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[custom-elements]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[shadow-dom]]></category>
            <dc:creator><![CDATA[Vipul Nema]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 08:50:57 GMT</pubDate>
            <atom:updated>2020-01-04T08:50:57.445Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Integration of web component in the application</strong></p><p>So if you are new to web component and just wondering what are they, when to use, how to use, are they supported in all browsers? then this blog can provide good external resource links. That would save your time, So let’s start quickly without wasting much time in searching.</p><p>Recently I had to create a system where different web pages can include configured dynamic widgets. Widget updation should be independent of those pages. In order to implement this, I explored web components and created an application around it.</p><p><strong>What is Web Component</strong></p><p>Web components are not new to the web, By defination — Web components are “encapsulated custom HTML elements” that are reusable, platform-independent, interoperable.</p><p>In a technical way we can say, They are -<strong>technology suit</strong> of the ‘<strong>Custom element’, ‘HTML template’, ‘Shadow Dom</strong>’. These technologies solve unique problems in web development. So if you know the use case of these technologies then congratulation you already know web components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*jSl_7nz1bdKUs9p7.png" /></figure><p>For more detail, you can reach below links</p><ol><li><a href="https://www.webcomponents.org/introduction">https://www.webcomponents.org/introduction</a></li><li><a href="https://developers.google.com/web/fundamentals/web-components">https://developers.google.com/web/fundamentals/web-components</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">https://developer.mozilla.org/en-US/docs/Web/Web_Components</a></li></ol><p><strong>First thing first — Browser support.</strong></p><p>Web component technologies are fully supported in chrome, firefox, safari. In other browsers(Edge, IE 11) they are working on it till then the good news is we have <a href="https://github.com/webcomponents/polyfills/tree/master/packages/webcomponentsjs">polyfills</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*H2r_95c2XQXBm8YzPwdfmQ.png" /></figure><p>How to build them -</p><ol><li>Add polyfill</li><li>Write component using native core code or use framework</li></ol><h3><strong>Add Polyfill</strong></h3><p>Below are the recommended links for polyfills.</p><ol><li><a href="https://github.com/webcomponents/polyfills/tree/master/packages/webcomponentsjs">https://github.com/webcomponents/polyfills/tree/master/packages/webcomponentsjs</a></li><li><a href="https://www.webcomponents.org/polyfills">https://www.webcomponents.org/polyfills</a></li><li><a href="https://developers.google.com/web/fundamentals/web-components/customelements#polyfill">https://developers.google.com/web/fundamentals/web-components/customelements#polyfill</a></li></ol><h3><strong>Write component using native core code or use framework</strong></h3><p>For writing native web components you should familiar with all technogy involved.</p><p><strong>HTML Template</strong></p><p>The HTML &lt;template&gt; element allows us to stamp out re-usable templates of code inside a normal HTML flow that won’t be immediately rendered, but can be used at a later time.</p><pre>&lt;template id=&quot;my-paragraph&quot;&gt;<br>  &lt;p&gt;My paragraph&lt;/p&gt;<br>&lt;/template&gt;</pre><p><a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements"><strong>Custom Elements</strong></a><strong> and Shadow Dom</strong> — Custome HTML elements with custom templates, behaviors and tag names</p><pre>//Define custome element</pre><pre>customElements.define(&#39;my-paragraph&#39;,<br>  class extends HTMLElement {<br>    constructor() {<br>      super();<br>      let template = document.getElementById(&#39;my-paragraph&#39;);<br>      let templateContent = template.content;</pre><pre>// define shadow dom<br>      const shadowRoot = this.attachShadow({mode: &#39;open&#39;})<br>        .appendChild(templateContent.cloneNode(true));<br>  }<br>})</pre><pre>//How to use use in html</pre><pre>&lt;template id=&quot;my-paragraph&quot;&gt;<br>  &lt;p&gt;My paragraph&lt;/p&gt;<br>&lt;/template&gt;</pre><pre>&lt;my-paragraph&gt;&lt;/my-paragraph&gt;</pre><p><strong>Framework </strong>provides much help in building any functionality. but there are mainly 3 drawbacks of any framework</p><ol><li>Learning curve</li><li>Bundle size</li><li>Library version changes</li></ol><p>But there are many pros too, below are some good frameworks that you can use. like lightweight ‘lit-element’ uses ‘lit-html’ that optimizes dom manipulation. I used it in my application and it is awesome.</p><ol><li><a href="https://lit-element.polymer-project.org/guide">https://lit-element.polymer-project.org/guide</a></li><li><a href="https://stenciljs.com/">https://stenciljs.com/</a></li></ol><p>Challenges in web components integration</p><ol><li>This is evolving and new technology. So it may be difficult to implement.</li><li>Due to private scope, data sharing and event tracking is difficult.</li><li>Polyfill required for IE11 and edge, below IE11 (IE-8,9,10)polyfill also not works.</li><li>SEO — Though google boat recently added full handling for web component but other crawlers may not handle it.(solution — puppeteer (v8)based rendering).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95778877151b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding service worker life cycle]]></title>
            <link>https://medium.com/@vipulnema2610/understanding-service-worker-life-cycle-b6580aa4eb50?source=rss-9f9fe01bf09f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6580aa4eb50</guid>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[browser-cache]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vipul Nema]]></dc:creator>
            <pubDate>Sun, 21 Jul 2019 17:01:21 GMT</pubDate>
            <atom:updated>2019-07-31T08:57:28.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*oOcY2Gn-LVt1h-e9xOv5oA.jpeg" /><figcaption><a href="https://www.google.com/imgres?imgurl=https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1600%2F1*oOcY2Gn-LVt1h-e9xOv5oA.jpeg&amp;imgrefurl=https%3A%2F%2Fwww.netlify.com%2Fblog%2F2018%2F09%2F21%2Finternational-service-worker-caching-awareness-day%2F&amp;docid=b1Hz3orWv--otM&amp;tbnid=LPe1AlDcC5TDvM%3A&amp;vet=10ahUKEwi23pfo-MzjAhXNbn0KHVD0AvYQMwh6KAEwAQ..i&amp;w=1600&amp;h=821&amp;safe=off&amp;bih=635&amp;biw=1366&amp;q=service%20worker&amp;ved=0ahUKEwi23pfo-MzjAhXNbn0KHVD0AvYQMwh6KAEwAQ&amp;iact=mrc&amp;uact=8">source</a></figcaption></figure><h3>What is service worker — It is a proxy worker between browser and server that intercept network request and respond accordingly, to provide nice offline user experience using browsers resource like — Cache, IndexDb, etc.</h3><p>Hello Friends, Here I am going to share my knowledge that I got while integrating service worker for resource caching (JS, CSS, fonts, images, etc) in my application.</p><p>To getting a better understanding of service workers, below are the things that you should be familiar with before you go further.</p><ol><li>Web Worker( <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers</a>)</li><li>Fetch( <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch</a>)</li><li>Browser Cache ( <a href="https://developer.mozilla.org/en-US/docs/Web/API/Cache">https://developer.mozilla.org/en-US/docs/Web/API/Cache</a>)</li><li>Promise( <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise</a>)</li><li>Https Cache-control headers( <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching">https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching</a>)</li><li>Old Caching mechanism — AppCache ( <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache">https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache</a>)</li></ol><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers"><strong>MDN </strong></a>and <strong>G</strong><a href="https://developers.google.com/web/fundamentals/primers/service-workers/"><strong>oogle dev</strong></a> are great sources of getting deep understanding. Below I am briefly some of the points.</p><p><a href="https://vipul-nema.github.io/demo-sw/">Small demo</a></p><p><strong>The main benefit of using service workers than old methods is that it runs on a different thread to the main JavaScript that powers your app, so it is not blocking.</strong></p><p>A service worker is run in a worker context: therefore it has no DOM access, It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can’t be used inside a service worker. Service workers only run over HTTPS or localhost, for security reasons( <em>man in the middle</em> attacks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*5l-2aP5-sWYjjnY0.png" /><figcaption>If Offline than serve from cache.</figcaption></figure><h3>Service worker life cycle — The below image from MDN nicely explains each step of the service worker’s life cycle.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*kRHfPL3v5s82N93N.png" /></figure><p>Every new thing seems tough in starting but when you got a better understanding of how it works conceptually it is so simple for you. For integrating this event-based logic that works in a different thread and handles your network calls. So for using it, we have to first register it. then it would start handling our page.</p><p>Registering incorporate below steps</p><ol><li>download file — it is done by register method.</li><li>install event — it is like a class constructor that fires once per service worker registration.</li><li>active event — helpfull in maintaining and clearing cache</li></ol><p>After a successful registration service worker is ready to control page under its scope by ‘fetch ’event.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>For registering the service worker</strong> you simply call serviceWorker.register method and give a path of the file where all service events(install, active, fetch, push, sync) are written which handle the things.</p><pre>navigator.serviceWorker.register(&#39;./sw-scope/sw.js&#39;, {scope: &#39;./sw-scope/&#39;})<br>  .then((reg) =&gt; {<br>    // registration worked<br>    console.log(&#39;Registration succeeded. Scope is &#39; + reg.scope);<br>  });</pre><p><strong>Scope </strong>— If we register the service worker file at /route1/sw.js, then the service worker would only see fetch events for pages whose URL starts with /route1/ (i.e. /route1/page1/, /route1/page2/). These pages are also called controlled pages.</p><p>While the registration process, <strong>install </strong>and <strong>active </strong>events fired in the background. These events run only once per the new update of service worker registration. After successful registration, fetch and other events fires while network request. Service worker remains ideal when it is not required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*f4lmvbFcuzd040bZ.png" /><figcaption>source — <a href="https://developers.google.com/web/fundamentals/primers/service-workers/">https://developers.google.com/web/fundamentals/primers/service-workers/</a></figcaption></figure><p><strong>Install </strong>— Inside of our install callback, we can do any action like below</p><p>Open a cache, Cache our files, Confirm whether all the required assets are cached or not.</p><pre>self.addEventListener(&#39;install&#39;, function(event) {<br>  // Perform install steps<br>  event.waitUntil(<br>   // Promise like cahce.open<br>  );<br>});</pre><p>caches.open() promise to create and open a browser cache with passed cache name, after which we call cache.addAll()and pass in our array of files. For more details — <a href="https://developer.mozilla.org/en-US/docs/Web/API/Cache/addAll">https://developer.mozilla.org/en-US/docs/Web/API/Cache/addAll</a></p><p><strong>Active </strong>— if install resolved with success then active event fires. After install, even a service worker is almost ready to work. But while updating the service worker logic, if you want to do some stuff before it starts to handle fetch events those work we can do here like below.</p><p>One common task that will occur in the activate callback is cache management. The reason you&#39;ll want to do this in the activate callback is that if you were to wipe out any old caches in the install step, any old service worker, which keeps control of all the current pages, will suddenly stop being able to serve files from that cache.</p><pre>self.addEventListener(&#39;activate&#39;, function(event) {<br>  event.waitUntil(<br>    caches.keys().then(function(cacheNames) {<br>      return Promise.all(<br>        cacheNames.filter(function(cacheName) {<br>          // Return true if you want to remove this cache,<br>          // but remember that caches are shared across<br>          // the whole origin<br>        }).map(function(cacheName) {<br>          return caches.delete(cacheName);<br>        })<br>      );<br>    })<br>  );<br>});</pre><p><strong>Fetch — </strong>After a service worker is installed and the user navigates to a different page or refreshes, the service worker will begin to receive fetch events</p><p>You can attach a fetch event listener to the service worker, then call the respondWith()method on the event to hijack our HTTP responses and update them with your own magic. for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.</p><pre>self.addEventListener(&#39;fetch&#39;, (event) =&gt; {<br>  event.respondWith(<br>    // magic goes here<br>    caches.match(event.request).then((response) =&gt; {<br>      return response || fetch(event.request);<br>    })<br>  );<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*JSbD0kL_WGfxEJ-V.png" /></figure><h3>How to update service worker —</h3><p>The latest browser checks each time whether the service worker file got updated or not, not matters what cache-control headers are there. If the file is not updated then old SW continue handle page but if changes then new service worker got register, but this is not guaranteed on old browsers versions so to update the service worker logic, make sure the file that you register and where all evens handling logic is written should not be cached in browser or server like at the backend server or at cdn handles.</p><p>If your application is not the offline app. which means you are not storing index.hml file in the cache, then you can easily update service worker file with versioning too. but it is not a good way.</p><p>new service worker logic only activated when there are no longer any pages loaded that are still using the old service worker. you can control this by <strong>self.skipWaiting.</strong></p><p><strong>Google workbox</strong> — Google workbox is a tool to easily integrate various caching strategies using service worker for PWA(progressive web app)</p><p><a href="https://developers.google.com/web/tools/workbox/">Workbox | Google Developers</a></p><p><strong>Opaque response</strong> — Be careful, if you store js script and CSS link, etc response in the browser cache, by default fetch request mode for these are no-cors. In that case, the response would be opaque which take 90 times more padding data in the cache. So 1MB data would be calculated as 90–100 MB data. so you may get an error like — quota exceeded.</p><p>More details — <a href="https://developers.google.com/web/tools/workbox/guides/storage-quota">https://developers.google.com/web/tools/workbox/guides/storage-quota</a></p><p>solution</p><ol><li>use the crossorigine attribute in each HTML resource, then default mode would be cors. you can add it webpack build too using this option. ( <a href="https://developers.google.com/web/tools/workbox/">https://developers.google.com/web/tools/workbox/</a>)</li><li>Convert fetch request mode ’no-cors’ to ‘cors’ manually, if server supporting cors enabled for your domain. most CDN are corn enabled.</li></ol><p><strong>Unregister/Uninstall service worker</strong> — In the project development lifecycle, there is a phase after development and QA, when you deploy or publish your application to users. On critical thing developers always do know how to revert changes in case of any bug.</p><p>The same is the case in registering service worker. Because it hijack your application, so if any buggy code is present inside the service worker you would have to unregister it with code.</p><pre>navigator.serviceWorker.getRegistration(&#39;/app&#39;).then(function(registrations) {<br>  for (let registration of registrations) {</pre><pre>    registration.unregister().then(function(boolean) {</pre><pre>       //if boolean = true, unregister is successful,</pre><pre>      //you have to delete cache if want</pre><pre>    });</pre><pre> }</pre><pre>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6580aa4eb50" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>