<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="/rss.xsl" type="text/xsl"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>chilledcowfan.io</title><description>Personal website by Anton Burduzha — a senior software engineer sharing deep dives into web development</description><link>https://chilledcowfan.io</link><item><title>Why localStorage Still Crashes Your Website in 2023</title><link>https://chilledcowfan.io/posts/localstorage-crash</link><guid isPermaLink="true">https://chilledcowfan.io/posts/localstorage-crash</guid><pubDate>Sat, 28 Jan 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In autumn 2022, I decided to migrate one of our work projects from the Create React App to NextJs. The goal of this was to increase the performance of a few pages, separate pages for mobile devices from the main app, and decrease the number of 3rd parties with access. Most of our goals were achieved successfully but according to our Airbrake notifier, localStorage was always breaking something. I hadn’t previously considered that localStorge would be a challenge, as I had been storing users’ phone numbers and i18n keys there and couldn&apos;t use a backend API instead.&lt;/p&gt;
&lt;p&gt;So, I needed localStorage to work since it was the only option for me.&lt;/p&gt;
&lt;h2&gt;My challenges&lt;/h2&gt;
&lt;p&gt;One problem I faced was an error at compile time.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ReferenceError: localStorage is not defined
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yeah, I was definitely a newbie to NextJs and totally missed the fact that my pages perform server render first and foremost. Meaning that &lt;code&gt;window&lt;/code&gt; and &lt;code&gt;localStorage&lt;/code&gt; wouldn&apos;t be accessible until the page is loaded on the client’s side.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useEffect } from &apos;react&apos;;

useEffect(() =&amp;gt; {
  const phoneNumber = localStorage.getItem(&apos;phoneNumber&apos;);
}, []);

// and
const onChange = (value) =&amp;gt; localStorage.setItem(&apos;phoneNumber&apos;, value);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The solution was quite simple, to put everything related to it into useEffect and onChange handlers to make sure it reflects in the browser.&lt;/p&gt;
&lt;p&gt;The second and the third were my biggest problems because I managed to solve them only after reading lots of articles, posts, and documentation pages.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SecurityError: The operation is insecure.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We received this error only from the Safari browser, so I decided to dig a little further. I found an interesting fact. If all cookies in privacy and security settings are blocked by the user, every time your website calls either &lt;code&gt;localStorage&lt;/code&gt; or &lt;code&gt;sessionStorage&lt;/code&gt; it will cause an error.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Even calling
console.log(localStorage);
// or
localStorage?.getItem(&apos;phoneNumber&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wrapping everything in &lt;code&gt;try...catch&lt;/code&gt; wasn’t a good option because it would increase the existing codebase, which is bad practice. Following the code snippet on &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API?ref=hackernoon.com#feature-detecting_localstorage&quot;&gt;MDN&lt;/a&gt;, I decided to write a utility class that would cover all vital components related to the &lt;code&gt;localStorage&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AppStorage {
  getItem(key) {
    if (this.storageAvailable()) {
      return window.localStorage?.getItem(key);
    }
    return undefined;
  }

  setItem(key, value) {
    if (this.storageAvailable()) {
      window.localStorage?.setItem(key, value);
    }
  }

  storageAvailable(type = &apos;localStorage&apos;) {
    let storage;
    try {
      storage = window[type];
      const x = &apos;__storage_test__&apos;;
      storage.setItem(x, x);
      storage.removeItem(x);
      return true;
    } catch (e) {
      return (
        e instanceof DOMException &amp;amp;&amp;amp;
        // everything except Firefox
        (e.code === 22 ||
          // Firefox
          e.code === 1014 ||
          // test name field too, because code might not be present
          // everything except Firefox
          e.name === &apos;QuotaExceededError&apos; ||
          // Firefox
          e.name === &apos;NS_ERROR_DOM_QUOTA_REACHED&apos;) &amp;amp;&amp;amp;
        // acknowledge QuotaExceededError only if there&apos;s something already stored
        storage &amp;amp;&amp;amp;
        storage.length !== 0
      );
    }
  }
}
// and inside our components
const phoneNumber = AppStorage.getItem(&apos;phoneNumber&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looks quite elegant, doesn’t it?&lt;/p&gt;
&lt;p&gt;We have this utility class in a separate file and can use it across the app by applying the &lt;a href=&quot;https://en.wikipedia.org/wiki/Don%27t_repeat_yourself&quot;&gt;DRY&lt;/a&gt; strategy. By the way, this utility class also helped to solve the last problem:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TypeError: Cannot read properties of null (reading &apos;setItem&apos;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Airbrake sent us that error from Android on new versions of Chrome. I still haven’t figured out what caused it, because the operator &lt;code&gt;.?&lt;/code&gt; didn&apos;t help, &lt;code&gt;window.localStorage&lt;/code&gt; was defined. But it was &lt;code&gt;null&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I really hope it will be fixed in the nearest months or years and Browser API will be unified across all browsers. Yes, I’m a dreamer. And of course, I believe this article and my experience will help someone who is struggling with &lt;code&gt;localStorage&lt;/code&gt; crashes.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Building Embeddable Widgets with TypeScript</title><link>https://chilledcowfan.io/posts/js-embeddable-widget</link><guid isPermaLink="true">https://chilledcowfan.io/posts/js-embeddable-widget</guid><pubDate>Mon, 30 Jan 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Sometimes, along with the main product, there is the need to create embeddable lightweight widgets, that your b2b customers can add to their website to show notifications, ads, quick chat functionality, etc.&lt;/p&gt;
&lt;p&gt;In this blog post, I will show how I implemented it for our product. You will have a ready-to-insert script that will download and run the bundle file. The main requirement for our widget is the minimum number of technologies to use. I chose web components and a Shadow DOM for this project.&lt;/p&gt;
&lt;h2&gt;What is Shadow DOM?&lt;/h2&gt;
&lt;p&gt;To cut a long story short, I would say that the Shadow DOM is a DOM with elements and styles that have their own scope. It is not affected by the main CSS of the website because it’s encapsulated. You can’t access the Shadow DOM elements with querySelector or other APIs and you don’t need to think about CSS collisions. Fantastic no?&lt;/p&gt;
&lt;p&gt;You might think iframes are the most popular form of scoped DOMs and it’s better to use them, but iframes have their own disadvantages, such as cors, and responsiveness.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Shadow DOM pros&lt;/th&gt;
&lt;th&gt;Shadow DOM cons&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Scoped DOM&lt;/td&gt;
&lt;td&gt;Compatibility&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Scoped CSS&lt;/td&gt;
&lt;td&gt;Using multiple Shadow DOM projectscan cause conflict with each other&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Composition&lt;/td&gt;
&lt;td&gt;Accessibility&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Performance&lt;/td&gt;
&lt;td&gt;Custom fonts&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;blockquote&gt;
&lt;p&gt;Just FYI, I’m going to include code snippets with explanations for each step, so that we can “code along” and figure it out bit by bit.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Also at the top of each snippet, you will find the name of the file, so you’re not confused about where to put it. But be careful not to copy it with the code, as it will cause an error for some extensions.&lt;/p&gt;
&lt;h2&gt;Setting up our project&lt;/h2&gt;
&lt;p&gt;Let’s start building our project by creating a folder called ”whatever name you like”. Please open a shell and execute&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm init
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then install our first dependencies. I hope you are already familiar with &lt;code&gt;webpack&lt;/code&gt; and know its purpose. Along with it, we&apos;re going to install Typescript for type checking and reducing the number of errors.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save-dev webpack webpack-cli webpack-dev-server typescript ts-loader html-webpack-plugin cross-env
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If everything is fine, let’s create a file in the root of our directory with the name tsconfig.json and the next config inside. It&apos;s just simple instruction, which explains to Typescript how to read our code. Nothing advanced. You can read about each line &lt;a href=&quot;https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;src&quot;,
    &quot;rootDir&quot;: &quot;.&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;target&quot;: &quot;es2015&quot;,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;lib&quot;: [&quot;esnext&quot;, &quot;es2017&quot;, &quot;ES2015&quot;, &quot;dom&quot;],
    &quot;sourceMap&quot;: true,
    &quot;declaration&quot;: false,
    &quot;declarationMap&quot;: false,
    &quot;noImplicitAny&quot;: true,
    &quot;strict&quot;: true,
    &quot;strictNullChecks&quot;: true,
    &quot;strictBindCallApply&quot;: true,
    &quot;strictFunctionTypes&quot;: true,
    &quot;typeRoots&quot;: [&quot;node_modules/@types&quot;],
    &quot;esModuleInterop&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true
  },
  &quot;include&quot;: [&quot;src/**/*&quot;]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next important part of our setup is configuring &lt;code&gt;webpack&lt;/code&gt; to compile all our stuff. Please create the file called &lt;code&gt;webpack.config.js&lt;/code&gt; in the root of the project directory. It comes with simple instructions for bundlers to transform our code into plain JS, CSS, etc.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const path = require(&apos;path&apos;);
const webpack = require(&apos;webpack&apos;);
const HTMLWebpackPlugin = require(&apos;html-webpack-plugin&apos;);

module.exports = {
  entry: {
    Widget: &apos;./src/index.ts&apos;,
  },
  mode: &apos;development&apos;,
  output: {
    library: &apos;Widget&apos;,
    libraryTarget: &apos;umd&apos;,
    libraryExport: &apos;default&apos;,
    path: path.resolve(__dirname, &apos;dist&apos;),
    filename: `widget.js`,
  },
  resolve: {
    extensions: [&apos;.ts&apos;, &apos;.js&apos;, &apos;.scss&apos;],
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [{ loader: &apos;ts-loader&apos; }],
      },
    ],
  },
  plugins: [
    new HTMLWebpackPlugin({ template: path.resolve(__dirname, &apos;index.html&apos;) }),
    new webpack.HotModuleReplacementPlugin(),
  ],
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To end up our setup - create basic &lt;code&gt;index.html&lt;/code&gt; and &lt;code&gt;index.ts&lt;/code&gt; files in the root as previous files and put the next code inside to check if everything works properly.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;console.log(1);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset=&quot;UTF-8&quot; /&amp;gt;
    &amp;lt;title&amp;gt;Widget&amp;lt;/title&amp;gt;
    &amp;lt;meta
      name=&quot;viewport&quot;
      content=&quot;width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0&quot;
    /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you see the result of &lt;code&gt;console.log&lt;/code&gt; in the browser, it appears that everything is functioning properly.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./image.png&quot; alt=&quot;Sentry issue&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The setup is finished. Congrats, finally we can start our development.&lt;/p&gt;
&lt;h2&gt;Development step&lt;/h2&gt;
&lt;p&gt;We can create custom HTML elements, described by our class, with their own methods and properties, events, and so on. There are two kinds of custom elements:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Autonomous custom elements&lt;/strong&gt; – “all-new” elements, extending the abstract &lt;code&gt;HTMLElement&lt;/code&gt; class.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Customized built-in elements&lt;/strong&gt; – extending built-in elements, like a customized button, based on &lt;code&gt;HTMLButtonElement&lt;/code&gt; etc.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this tutorial, we need autonomous elements. To create a custom element, we need to tell the browser several details about it: how to show it, what to do when the element is added or removed from the page, etc. This is done by creating a class with special methods, which is easy to do, as there are only a few methods, and all of them are optional.&lt;/p&gt;
&lt;p&gt;A browser calls the method &lt;code&gt;connectedCallback&lt;/code&gt; when the element is added to the document. At that moment we create the &lt;code&gt;template&lt;/code&gt; element and put our markup inside with &lt;code&gt;innerHTML&lt;/code&gt; property. A built-in &lt;code&gt;template&lt;/code&gt; element serves as storage for HTML markup templates. The browser ignores its contents and only checks for syntax validity, but we can access and use it in JavaScript to create other elements. &lt;code&gt;this.shadowDocument&lt;/code&gt; is a document fragment that is attached to the main element.&lt;/p&gt;
&lt;p&gt;To create a Shadow DOM for an element, we call &lt;code&gt;this.attachShadow()&lt;/code&gt;. The next snippet gives you more understanding of what element we attach to the &lt;code&gt;template.content&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export const WidgetElement = () =&amp;gt; {
  class WidgetElement extends HTMLElement {
    constructor() {
      super();
      this.shadowDocument = this.attachShadow({ mode: &apos;open&apos; });
    }

    private shadowDocument: ShadowRoot;

    connectedCallback(): void {
      const template = document.createElement(&apos;template&apos;);
      template.innerHTML = &apos;&amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;&apos;;
      this.shadowDocument?.appendChild(template.content.cloneNode(true));
    }
  }

  return WidgetElement;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Please remove &lt;code&gt;console.log&lt;/code&gt; from the &lt;code&gt;index.ts&lt;/code&gt; file and simply copy and paste the code below. Our next step is defining the custom web component and its custom element. Let it be &lt;code&gt;&amp;lt;custom-widget&amp;gt;&amp;lt;/custom-widget&amp;gt;&lt;/code&gt;. We create an element &lt;code&gt;custom-widget&lt;/code&gt; that is going to be our root and attach WidgetElement (&lt;code&gt;template&lt;/code&gt; content) to it.&lt;/p&gt;
&lt;p&gt;Below, we invoke our code and show the new tag by appending it to the end of the body of the website.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { WidgetElement } from &apos;./WidgetElement&apos;;

const App = (() =&amp;gt; {
  const scriptEl = document.getElementById(&apos;top-widget&apos;);
  if (scriptEl) {
    if (!customElements.get(&apos;custom-widget&apos;)) {
      customElements.define(&apos;custom-widget&apos;, WidgetElement());
    }

    const componentInstance = document.createElement(&apos;custom-widget&apos;, {
      is: &apos;custom-widget&apos;,
    });

    const container = document.body;
    container.appendChild(componentInstance);
  }
})();

export default App;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Simply put the script below to &lt;code&gt;index.html&lt;/code&gt; instead of the tag &lt;code&gt;&amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script id=&quot;top-widget&quot;&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The result will be the same, see the picture below, but using the custom web component created with the Shadow DOM.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./image-2.png&quot; alt=&quot;Sentry issue&quot; /&gt;&lt;/p&gt;
&lt;p&gt;We’ve mentioned one of the Shadow DOM advantages before - Scoped CSS. I spent a fair amount of time to decide the best way to style web components and realized that there were none. As always, it depends on your experience, knowledge, stack, etc. All we really need is to find a way to get CSS and deliver inside &lt;code&gt;style&lt;/code&gt; tags at the top of our root.&lt;/p&gt;
&lt;p&gt;I&apos;m going to show my option, which in my personal opinion isn&apos;t bad at all. Please install the next dependencies and let&apos;s apply them one by one.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save-dev css-loader node-sass sass-loader sass-to-string
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Reading and transforming Sass to CSS, &lt;code&gt;webpack&lt;/code&gt; requires adding the following loaders. &lt;code&gt;sass-to-string&lt;/code&gt; is required to take styles and use them as a plain string. You will see how Sass will be imported and inserted into the template.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// add those options under ts-loader config
{
    test: /\.scss$/,
    exclude: /node_modules/,
    use: [
        &apos;sass-to-string&apos;,
        {
            loader: &apos;sass-loader&apos;,
            options: {
                sassOptions: {
                    outputStyle: &apos;compressed&apos;,
                },
            },
        },
    ],
},
{
    test: /\.css$/,
    use: [&apos;css-loader&apos;],
},
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we’re creating a new directory called &lt;code&gt;styles&lt;/code&gt; with &lt;code&gt;main.scss&lt;/code&gt; file inside. Just copy and paste the example inside. You&apos;ll easily change styles later, or forget, play with them whichever way you want.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.widget {
  width: 240px;
  height: 80px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  p {
    margin: 0;
    color: gray;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To prevent the mixing of logic in one file, let’s create a new one with the name &lt;code&gt;widget.template.ts&lt;/code&gt; and add a new markup with predefined CSS classes to it. Previously we explained &lt;code&gt;webpack&lt;/code&gt; what to do with Sass in our project, so just import the &lt;code&gt;main.scss&lt;/code&gt;example code at the top of the file. Don&apos;t forget to add the new declaration to the new globals.d.ts file in the root of &lt;code&gt;src&lt;/code&gt; directory for &lt;code&gt;.scss&lt;/code&gt; files.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import styles from &apos;./styles/main.scss&apos;;

const renderTemplate = () =&amp;gt; {
  return `
            &amp;lt;style&amp;gt;${styles}&amp;lt;/style&amp;gt;
            &amp;lt;div class=&quot;widget&quot;&amp;gt;
                &amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;
            &amp;lt;/div&amp;gt;
        `;
};

export { renderTemplate };
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;declare module &apos;*.scss&apos; {
  export default {};
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At the end of this part, we import the template and substitute an old plain string &lt;code&gt;p&lt;/code&gt; tag with it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// add import at the top of the file
import { renderTemplate } from &apos;./widget.template&apos;;

// update existing method
private appendShadowDOMWithData = (): void =&amp;gt; {
    const template = document.createElement(&apos;template&apos;);
    template.innerHTML = renderTemplate();
    this.shadowDocument?.appendChild(template.content.cloneNode(true));
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;During this step, we already have an idea about the style of our future widget. Let’s add some icons inside our component. It’s hard to imagine any widget without awesome icons or pictures. I suggest adding some to our widget as well, just in case you will be struggling with it. I found a simple star SVG image.&lt;/p&gt;
&lt;p&gt;Put your valid SVG icon into a new folder &lt;code&gt;assets/[name-of-your-svg].svg&lt;/code&gt; and import it inside our &lt;code&gt;widget.template.ts&lt;/code&gt; file. Don&apos;t forget to tell &lt;code&gt;webpack&lt;/code&gt; to recognize it and add new instructions to &lt;code&gt;globals.d.ts&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// add this option under css-loader config
{
    test: /\.(png|svg|jpg|jpeg|gif)$/i,
    type: &apos;asset/resource&apos;,
},
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import star from &apos;./assets/star.svg&apos;;

// and below
&amp;lt;div class=&quot;widget&quot;&amp;gt;
    &amp;lt;img src=&quot;${star}&quot; alt=&quot;star&quot; /&amp;gt;
    &amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;declare module &apos;*.svg&apos; {
  export default {};
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step is changing our font. To be honest, I didn’t find any information on how to add fonts inside of the Shadow DOM project and apply them. But there is still access to Google fonts. I created a script that allows us to download the necessary font. We use Rubik as the main font in our product, so let’s take it here as well.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const FONT_FACE = `@import url(&apos;https://fonts.googleapis.com/css2?family=Rubik:wght@400;500&amp;amp;display=swap&apos;);`;

export const setupFontFaces = () =&amp;gt; {
  if (document.querySelector(&apos;style[data-description=&quot;font-faces&quot;]&apos;)) {
    return;
  }
  const style = document.createElement(&apos;style&apos;);
  style.dataset.description = &apos;font-faces&apos;;

  style.appendChild(document.createTextNode(FONT_FACE));
  document.head.appendChild(style);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the snippet above we create &lt;code&gt;style&lt;/code&gt; element in the outer scope and import google Fonts via the link. Nothing special, I tested it several times and it didn&apos;t make any collisions with the main website. The next step is to call our &lt;code&gt;setupFontFaces&lt;/code&gt; function during the initialization of the widget.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { setupFontFaces } from &apos;./setupFonts&apos;;

// and add inside our constructor
constructor() {
    super();
    setupFontFaces();
    this.shadowDocument = this.attachShadow({ mode: &apos;open&apos; });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you open the network tab in the browser web tools, you’ll see that Rubik web font was downloaded.&lt;/p&gt;
&lt;p&gt;And here we are!&lt;/p&gt;
&lt;p&gt;Just add it either globally or to a specific selector.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;body {
  font-family: &apos;Rubik&apos;;
}
p {
  margin: 0;
  font-family: &apos;Rubik&apos;;
  color: gray;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All that is left is to add &lt;code&gt;position: absolute;&lt;/code&gt; and position styles to our element to make it look like a real widget. The last and main part is building our project. Run &lt;code&gt;npm run build&lt;/code&gt; and look inside the &lt;code&gt;dist&lt;/code&gt; folder. There is a file &lt;code&gt;Widget.min.js&lt;/code&gt;. Below there is an example of how another website can access your file. Just put it somewhere on the bucket or server and serve it under some URL.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script id=&quot;top-widget&quot; src=&quot;YOUR_BUCKET_URL/Widget.min.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Great, we have finished this simple but cool project. Just imagine what interesting embeddable widgets you can build with the help of this example.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>How to Upload Source Maps to Sentry with Next.js</title><link>https://chilledcowfan.io/posts/next-sentry-sourcemaps</link><guid isPermaLink="true">https://chilledcowfan.io/posts/next-sentry-sourcemaps</guid><pubDate>Mon, 06 Feb 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Nowadays every modern web application uses platforms that provide error monitoring in real-time. They have support for different languages and technologies. And that’s great because the quality of development grows every year.&lt;/p&gt;
&lt;p&gt;I’m a big fan of tools that help my team instantly react to bugs and crashes and fix them ASAP. It’s necessary when you are building a startup and trying to show your customers the best service. For instance, we used to monitor our frontend errors in &lt;code&gt;Airbrake&lt;/code&gt; and fixed repeated crashes for the mobile Safari browser. That was a big win because I had started to hate that issue (everyone faced that issue which cost him plenty of hours to find the solution). Recently, my team made the decision to migrate our front-end projects from &lt;code&gt;Airbrake&lt;/code&gt; to &lt;code&gt;Sentry&lt;/code&gt;. And like a big part of other developers, I was struggling with uploading source maps there.&lt;/p&gt;
&lt;p&gt;I think the following solutions can help those who have &lt;code&gt;~Next.js@12&lt;/code&gt; and &lt;code&gt;~@sentry/nextjs@7.3+&lt;/code&gt; versions on their projects.&lt;/p&gt;
&lt;h2&gt;Solution 1&lt;/h2&gt;
&lt;p&gt;If you see a notification similar to that in the picture below on an Issue page inside Sentry don’t fret. &lt;code&gt;@sentry/nextjs&lt;/code&gt; skipped the uploading of some source maps for Next.js generated files. In my case, those were errors that related to the framework/main files.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./image.png&quot; alt=&quot;Sentry issue&quot; /&gt;&lt;/p&gt;
&lt;p&gt;A little explanation: When Sentry is reacting to any error or event, it tries to get the source maps from the &lt;code&gt;release&lt;/code&gt; archive that it has uploaded. According to the GitHub issue conversation, the framework&apos;s code does not get uploaded by default anymore and Sentry doesn’t have access to all files for resolving stack trace.&lt;/p&gt;
&lt;p&gt;Take a look at this note from Sentry manual setup documentation:&lt;/p&gt;
&lt;p&gt;:::important
If you find that there are in-app frames in your client-side stack traces that aren&apos;t getting source-mapped even when most others are, it&apos;s likely because they are from files in &lt;code&gt;static/chunks/&lt;/code&gt; rather than &lt;code&gt;static/chunks/pages/&lt;/code&gt;. By default, such files aren&apos;t uploaded because the majority of the files in &lt;code&gt;static/chunks/&lt;/code&gt; only contain Next.js or third-party code, and are named in such a way that it&apos;s hard to distinguish between relevant files (ones containing your code) and irrelevant ones.
:::&lt;/p&gt;
&lt;p&gt;To make it upload everything, try to expand your current &lt;code&gt;next.config.js&lt;/code&gt; with the next properties.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;module.exports = withSentryConfig(
  {
    ...yourNextConfig,
    sentry: {
      widenClientFileUpload: true,
    },
  },
  {
    ...yourWebpackSentryConfig,
    ignore: [],
  },
  yourSentryConfig,
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It helped me to resolve 2 of the 3 errors that I got. For the majority, it’ll solve 100% of problems with source maps.&lt;/p&gt;
&lt;h2&gt;Solution 2&lt;/h2&gt;
&lt;p&gt;Let’s move on. The last problem was related to a square brackets notation for dynamic route values. If I catch an error on the client side(browser side), the stack trace paths are sent encoded but they’re not decoded when they reach the sentry server. Since the path is encoded and the string &lt;code&gt;%5Bslug%5D.js&lt;/code&gt; is not equal to &lt;code&gt;[slug].js&lt;/code&gt;, the source map is not matched/not found/whatever. When Sentry is sending the frames, it includes this encoded URL instead of the decoded URL.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I’ve found the solution in rewriting StackFrame.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Just follow the next instructions. Install &lt;code&gt;@sentry/integrations&lt;/code&gt; package to expand your current client config.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save @sentry/integrations
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import { RewriteFrames } from &apos;@sentry/integrations&apos;;

Sentry.init({
  ...yourSentryClientConfig,
  integrations: [
    ...yourSentryClientConfig.integrations,
    new RewriteFrames({
      iteratee: (frame) =&amp;gt; {
        frame.filename = frame.filename.replace(distDir, &apos;app:///_next&apos;);
        // here we are decoding our square brackets []
        frame.filename = decodeURI(frame.filename);
        return frame;
      },
    }),
  ],
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Great! I hope this solves at least one person’s problems!&lt;/p&gt;
&lt;p&gt;As new technologies constantly evolve, their versions get mismatched and make many developers cry. But god bless a huge programmer community that is glad to share their experience with others.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Implementing i18n in Next.js: A Guide to Non-Route-Based Localization</title><link>https://chilledcowfan.io/posts/next-non-route-i18n</link><guid isPermaLink="true">https://chilledcowfan.io/posts/next-non-route-i18n</guid><pubDate>Wed, 22 Feb 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Motivation&lt;/h2&gt;
&lt;p&gt;Recently, we migrated our sub-project from &lt;code&gt;react-localization&lt;/code&gt; to &lt;code&gt;i18next&lt;/code&gt;. During that migration, the main goal was to keep the previous behavior of setting and changing language in our app.&lt;/p&gt;
&lt;p&gt;Storing language in a route path is a commonly used practice for the Nextjs framework. But for our project, that was an inappropriate solution. Our main application allows businesses to generate QR codes for their customers with a link to the sub-application where the end user can leave feedback regarding service quality and satisfaction. All QR codes had already been printed, and new ones would cost a fortune for the business. The previous version of the sub-app used to be built on the base of CRA, and only half a year ago, it was migrated to Nextjs. So, we were looking for library or libraries which could provide us with non-route-based internationalization and API similar to &lt;code&gt;react-i18next&lt;/code&gt;. We found &lt;code&gt;ni18n&lt;/code&gt;. This is a library specifically designed for use with Nextjs. &lt;code&gt;ni18n&lt;/code&gt; provides a simple and flexible way to add i18n functionality to Nextjs projects, including support for server-side rendering and other advanced features.&lt;/p&gt;
&lt;h2&gt;Basic Setup&lt;/h2&gt;
&lt;p&gt;Let’s install all necessary dependencies to start working on our project.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install i18next react-i18next ni18n
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step is to expand the existing &lt;code&gt;next.config.js&lt;/code&gt; with the default i18n config.&lt;/p&gt;
&lt;p&gt;Basically, we need only a few fields for a quick start. &lt;code&gt;locales&lt;/code&gt; is required to show all the locales we want to support in the app, and &lt;code&gt;defaultLocale&lt;/code&gt; will be used when visiting a non-locale prefixed path (for us, it’s just the default language).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;module.exports = {
  ...yourNextConfig,
  i18n: {
    defaultLocale: &apos;GB&apos;,
    locales: [&apos;GB&apos;, &apos;UA&apos;, &apos;PT&apos;],
  },
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we are required to create a new file in the root or utils/plugins/etc. directory named &lt;code&gt;ni18n.config.js&lt;/code&gt;. &lt;code&gt;supportedLngs&lt;/code&gt; - names which show us supported languages, and &lt;code&gt;ns&lt;/code&gt; - namespaces, which we can use in some cases.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export const ni18nConfig = {
  supportedLngs: [&apos;GB&apos;, &apos;UA&apos;, &apos;PT&apos;],
  ns: [&apos;namespace-name&apos;],
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A few more things left. Our application requires &lt;code&gt;I18nextProvider&lt;/code&gt;, so let’s wrap the &lt;code&gt;App&lt;/code&gt; with the high-order component imported from &lt;code&gt;i18n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;It will initialize the &lt;code&gt;i18nex&lt;/code&gt; instance and provide it as a context for all the children.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { appWithI18Next } from &apos;ni18n&apos;;
import { ni18nConfig } from &apos;../ni18n.config&apos;;

const App = ({ Component, pageProps }) =&amp;gt; &amp;lt;Component {...pageProps} /&amp;gt;;

export default appWithI18Next(App, ni18nConfig);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And the last preparation step before we started using translation into our components is a filling of translation files. The important thing - keep the following file structure.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;└── locales
    ├── GB
    │   ├── namespace-name.json  // { &quot;key1&quot;: &quot;Test&quot; }
    │
    ├── UA
    │   ├── namespace-name.json  // { &quot;key1&quot;: &quot;Тест&quot; }
    │
    ├── PT
		    ├── namespace-name.json  // { &quot;key1&quot;: &quot;Teste&quot; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, we’ve done with the setup and are ready to start integration of the i18n feature into components. Let’s take a look at the example in &lt;code&gt;ComponentName.jsx&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We extract the &lt;code&gt;t&lt;/code&gt; function from &lt;code&gt;useTranslation&lt;/code&gt; hook which will return translated string for the selected language. Looks simple, doesn’t it?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useTranslation } from &apos;react-i18next&apos;;

export const MyComponent = () =&amp;gt; {
  const { t } = useTranslation();
  return &amp;lt;div&amp;gt;{t(&apos;key1&apos;)}&amp;lt;/div&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you store user language in DB, don’t forget to create a context with &lt;code&gt;React.Context&lt;/code&gt; or any other solution to wrap pages and set the language in &lt;code&gt;useEffect&lt;/code&gt;. Below, I’ll show you a simple snippet of how it could be implemented.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const I18nProvider = ({ children, data }) =&amp;gt; {
  const { i18n } = useTranslation();

  const { language = &apos;GB&apos; } = data;

  useEffect(() =&amp;gt; {
    i18n.changeLanguage(language);
  }, [language]);

  return &amp;lt;I18nContext.Provider&amp;gt;{children}&amp;lt;/I18nContext.Provider&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That’s it. I hope it helped you to save some time, as always. In the future, we are going to migrate the existing i18n approach to route based. The reason is pretty simple - a unification of all our applications. I’ll definitely describe it in one of my next articles.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Next.js and SignalR: Effortless Socket Integration and Troubleshooting</title><link>https://chilledcowfan.io/posts/next-signalr-issue</link><guid isPermaLink="true">https://chilledcowfan.io/posts/next-signalr-issue</guid><pubDate>Wed, 06 Sep 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A minority, but still a massive number of projects, require web sockets integration to provide instant reaction of an interface on changes without re-fetching data.&lt;/p&gt;
&lt;p&gt;It’s an essential thing, and we are not going to talk about them or make a comparison between 3rd-party libraries that provide API for a better dev experience.&lt;/p&gt;
&lt;p&gt;My goal is to show how to integrate quickly &lt;code&gt;@microsoft/signalr&lt;/code&gt; with NextJs. And how to solve the problems we faced during development.&lt;/p&gt;
&lt;p&gt;I hope everyone has already installed and deployed the NextJS project locally. In my case, the version is &lt;code&gt;13.2.4&lt;/code&gt;. Let’s add some more important libraries: &lt;code&gt;swr&lt;/code&gt; (version &lt;code&gt;2.1.5&lt;/code&gt;) for data fetching and further work with the local cache and &lt;code&gt;@microsoft/signalr&lt;/code&gt; (version &lt;code&gt;7.0.5&lt;/code&gt;) - API for web sockets.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save @microsoft/signalr swr
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s start with creating a simple fetcher function and a new hook called &lt;code&gt;useChatData&lt;/code&gt; to get initial data from our REST API. It returns a list of the messages for the chat, fields that detect errors and loading state, and the method &lt;code&gt;mutate&lt;/code&gt; that allows to change cached data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import useSWR from &apos;swr&apos;;

type Message = {
  content: string;
  createdAt: Date;
  id: string;
};

async function fetcher&amp;lt;TResponse&amp;gt;(url: string, config: RequestInit): Promise&amp;lt;TResponse&amp;gt; {
  const response = await fetch(url, config);
  if (!response.ok) {
    throw response;
  }
  return await response.json();
}

export const useChatData = () =&amp;gt; {
  const { data, error, isLoading, mutate } = useSWR&amp;lt;Message[]&amp;gt;(&apos;OUR_API_URL&apos;, fetcher);
  return {
    data: data || [],
    isLoading,
    isError: error,
    mutate,
  };
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To test that it works as it is supposed, let’s update our page component. Import our hook at the top, and extract data from it like in the snippet below. If it works, you will see rendered data. As you see, it’s quite simple.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useChatData } from &apos;hooks/useChatData&apos;;

const Chat: NextPage = () =&amp;gt; {
	const { data } = useChatData();

	return (
		&amp;lt;div&amp;gt;
            {data.map(item =&amp;gt; (
                &amp;lt;div key={item.id}&amp;gt;{item.content}&amp;lt;/div&amp;gt;
             ))}
        &amp;lt;/div&amp;gt;
	);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step requires connecting our future page to web sockets, catching &lt;code&gt;NewMessage&lt;/code&gt; events, and updating a cache with a new message. I propose to start with building the socket service in a separate file.&lt;/p&gt;
&lt;p&gt;According to the examples in SignalR docs, we have to create an instance of connection for further listening to events. I also added a connections object for preventing duplicates and two helpers to start/stop the connections.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { HubConnection, HubConnectionBuilder, LogLevel } from &apos;@microsoft/signalr&apos;;

let connections = {} as {
  [key: string]: { type: string; connection: HubConnection; started: boolean };
};

function createConnection(messageType: string) {
  const connectionObj = connections[messageType];
  if (!connectionObj) {
    console.log(&apos;SOCKET: Registering on server events &apos;, messageType);
    const connection = new HubConnectionBuilder()
      .withUrl(&apos;API_URL&apos;, {
        logger: LogLevel.Information,
        withCredentials: false,
      })
      .withAutomaticReconnect()
      .build();

    connections[messageType] = {
      type: messageType,
      connection: connection,
      started: false,
    };
    return connection;
  } else {
    return connections[messageType].connection;
  }
}

function startConnection(messageType: string) {
  const connectionObj = connections[messageType];
  if (!connectionObj.started) {
    connectionObj.connection
      .start()
      .catch((err) =&amp;gt; console.error(&apos;SOCKET: &apos;, err.toString()));
    connectionObj.started = true;
  }
}

function stopConnection(messageType: string) {
  const connectionObj = connections[messageType];
  if (connectionObj) {
    console.log(&apos;SOCKET: Stoping connection &apos;, messageType);
    connectionObj.connection.stop();
    connectionObj.started = false;
  }
}

function registerOnServerEvents(
  messageType: string,
  callback: (payload: Message) =&amp;gt; void,
) {
  try {
    const connection = createConnection(messageType);
    connection.on(&apos;NewIncomingMessage&apos;, (payload: Message) =&amp;gt; {
      callback(payload);
    });
    connection.onclose(() =&amp;gt; stopConnection(messageType));
    startConnection(messageType);
  } catch (error) {
    console.error(&apos;SOCKET: &apos;, error);
  }
}

export const socketService = {
  registerOnServerEvents,
  stopConnection,
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So now, our page might look like in the code snippet. We fetch and extract &lt;code&gt;data&lt;/code&gt; with the list of messages and render them. Also, &lt;code&gt;useEffect&lt;/code&gt; above registers the &lt;code&gt;NewMessage&lt;/code&gt; event, creates a connection, and listens to the backend.&lt;/p&gt;
&lt;p&gt;When the event triggers, the &lt;code&gt;mutate&lt;/code&gt; method from the hook updates the existing list with a new object.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useChatData } from &apos;hooks/useChatData&apos;;
import { socketService } from &apos;api/socket&apos;;

const Chat: NextPage = () =&amp;gt; {
	const { data } = useChatData();

	useEffect(() =&amp;gt; {
        socketService.registerOnServerEvents(
            &apos;NewMessage&apos;,
            (payload: Message) =&amp;gt; {
                mutate(() =&amp;gt; [...data, payload], { revalidate: false });
            }
        );
    }, [data]);

	useEffect(() =&amp;gt; {
        return () =&amp;gt; {
            socketService.stopConnection(&apos;NewMessage&apos;);
        };
    }, []);

	return (
		&amp;lt;div&amp;gt;
            {data.map(item =&amp;gt; (
                &amp;lt;div key={item.id}&amp;gt;{item.content}&amp;lt;/div&amp;gt;
            ))}
        &amp;lt;/div&amp;gt;
	);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looks good to me, it works, and we see how new messages appear in the feed. I chose the basic example with chat because it’s clear and easy to understand. And, of course, you apply it on your own logic.&lt;/p&gt;
&lt;h3&gt;Small Bonus&lt;/h3&gt;
&lt;p&gt;Using one of the versions (&lt;code&gt;@microsoft/signalr&lt;/code&gt;), we faced a problem with duplications. It was connected to &lt;code&gt;useEffect&lt;/code&gt;, the dependency array. Each time the dependency was changed, &lt;code&gt;connection.on(event, callback);&lt;/code&gt; cached callback and triggered it again and again.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  // data equals [] by default (registerOnServerEvents 1 run),
  // but after initial data fetching it changes (registerOnServerEvents 2 run)
  // each event changes data and triggers running of registerOnServerEvents
  socketService.registerOnServerEvents(
    &apos;NewMessage&apos;,
    // callback cached
    (payload: Message) =&amp;gt; {
      // mutate called multiple times on each data change
      mutate(() =&amp;gt; [...data, payload], { revalidate: false });
    },
  );
}, [data]);
// after getting 3 messages events, we had got 4 messages rendered lol
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The quickest and most reliable solution we found was keeping a copy of data inside the React &lt;code&gt;ref&lt;/code&gt; and using it inside &lt;code&gt;useEffect&lt;/code&gt; for future updates.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useChatData } from &apos;hooks/useChatData&apos;;
import { socketService } from &apos;api/socket&apos;;

const Chat: NextPage = () =&amp;gt; {
	const { data } = useChatData();
	const messagesRef = useRef&amp;lt;Message[]&amp;gt;([]);

	useEffect(() =&amp;gt; {
	     messagesRef.current = chatData;
    }, [chatData]);

	useEffect(() =&amp;gt; {
        socketService.registerOnServerEvents(
            &apos;NewMessage&apos;,
            (payload: Message) =&amp;gt; {
			    const messagesCopy = messagesRef.current.slice();
                mutate(() =&amp;gt; [...messagesCopy, payload], { revalidate: false });
            }
        );
    }, [data]);

	useEffect(() =&amp;gt; {
        return () =&amp;gt; {
            socketService.stopConnection(&apos;NewMessage&apos;);
        };
    }, []);

	return (
		&amp;lt;div&amp;gt;
            {data.map(item =&amp;gt; (
                &amp;lt;div key={item.id}&amp;gt;{item.content}&amp;lt;/div&amp;gt;
            ))}
        &amp;lt;/div&amp;gt;
	);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Currently, we use a new version of &lt;code&gt;@microsoft/signalr&lt;/code&gt; which it seems already has necessary fixes. But anyway, if someone finds this solution useful and uses this workaround, I will be happy. To conclude, I want to say that my experience with SignalR is quite positive, installation didn’t require any specific dependencies or settings, and it works fine and covers our needs.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item></channel></rss>