<?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 Tugay İlik on Medium]]></title>
        <description><![CDATA[Stories by Tugay İlik on Medium]]></description>
        <link>https://medium.com/@tugayilik?source=rss-22f4a898748b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bhgJgHQkdvU3gGJN_kOyTg.png</url>
            <title>Stories by Tugay İlik on Medium</title>
            <link>https://medium.com/@tugayilik?source=rss-22f4a898748b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:55:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tugayilik/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[Creating Cloudwatch alarms over Metric Filters]]></title>
            <link>https://tugayilik.medium.com/creating-cloudwatch-alarms-over-metric-filters-1ba7465a1776?source=rss-22f4a898748b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba7465a1776</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <dc:creator><![CDATA[Tugay İlik]]></dc:creator>
            <pubDate>Sun, 23 May 2021 10:08:06 GMT</pubDate>
            <atom:updated>2021-05-23T16:08:32.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*xv9dpO-e5r2DD0AE.jpg" /><figcaption>A photo from <a href="http://www.freepik.com/">freepik.com</a></figcaption></figure><p><strong><em>CloudWatch</em></strong> collects monitoring and operational data in the form of logs, metrics, and events, providing you with a unified view of AWS resources, applications, and services that run on AWS and on-premises servers. You can use CloudWatch to detect anomalous behavior in your environments, set alarms, visualize logs and metrics side by side, take automated actions, troubleshoot issues, and discover insights to keep your applications<br>running smoothly.</p><p>There are a lot of metrics that can be used in Cloudwatch alarms by default. For example, I can get an insight into Lambda’s duration, errors, throttles, invocations, and concurrent execution by default. But I needed to track memory usage in case it reaches the limit. By default, it triggers invocation error when memory reaches the limit, but there are thousands of invocations happening in a short period of time, so it was really tough to find the exact error cause.</p><p><strong>Metric Filters</strong> come in handy in my case. You can search and filter the log data coming to CloudWatch Logs by creating one or more metric filters.</p><p>To compare memory allocation and usage, I needed to create two metric filters<strong> </strong>by using my lambda’s logs. The first one is for allocated memory and the other one is for memory usage.</p><p>To create metrics filters;</p><ol><li>Go Cloudwatch dashboard.</li><li>From the left menu, navigate <strong>Log groups</strong> and find your log group for your lambda function.</li><li>In the Log group, click the <strong>Metric Filters</strong> tab below and create a new metric filter.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJP-lVFQxg--6id4RI8-MQ.png" /></figure><p>Next, on the creation screen;</p><ol><li>The Filter pattern refers to the search query of the metric filter. Basically, what you wrote there is used for filtering the logs. In my case, I needed to extract the Memory Usage string from many verbal logs. To achieve that I used <strong>[…] </strong>filter to convert logs, into regex matches.</li><li>In the <strong>Test pattern </strong>section, I tested my filter pattern if it works or not. So the <strong>$18 </strong>regex group is exactly what I need. Noted down, because I will use it on the next page. After seeing it successfully working, click next.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*l1vgCY9lEQbO41v8Dd4WHg.png" /></figure><p>And we reached the last page of metric filter creation where we put the details for our custom metric.</p><ol><li><strong>Filter name,</strong> at the top, is used for searching your metric when adding an alarm, etc. In my case, I’ve written <strong>memory-usage.</strong></li></ol><p>In the <strong>Metric details</strong> section;</p><ol><li><strong>Metric namespace</strong>; This is used for grouping up your metrics in Cloudwatch. So, when you track similar metrics, you can simply write the common name. So, I’ve written <strong>&lt;lambda_name&gt;MemoryMetrics. </strong>It’s again, will appear when you search for Cloudwatch metrics. Setting proper and unique naming will be helpful.</li><li><strong>Metric name; </strong>A unique name specifically for this metric filter. I set <strong>MemoryUsage</strong> as a metric name. It must be unique in your Metric namespace. For another metric, you can’t use MemoryUsage naming again.</li><li><strong>Metric value;</strong> is the most critical one because our metrics will be based on this value. In the section above, we’ve saved our filter pattern’s regex group match, which is <strong>$18 </strong>for memory usage. So, I’ve written <strong>$18</strong> to this input.</li><li><strong>Default value (optional); </strong>Is the value published when the filter pattern does not match anything. I’ve left it empty.</li><li><strong>Unit (optional)</strong>; is the unit that is gonna be used for your metric. I leave it empty since I will use the value of my filter match.</li><li><strong>Dimensions:</strong> Identity of your metric. A name/value pair. A filter metric can have up to 3 dimensions. Used for searching and grouping purposes of your metric filter. I’ve left it empty since I search my filter by the name of it.</li><li>Click next, review and save your alarm.</li></ol><p>Now we have created our metric filter successfully. To compare it with another metric, I followed the same steps for the <strong>Memory Allocation </strong>metric. The regex match value for Memory Allocation was <strong>$13</strong>.</p><p>Now we can add alarms by using this filter. So we go and create a new alarm on Cloudwatch by searching this filter;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRV29YpR4CYvcWe-W4qclw.png" /><figcaption>Search result of our filter metric in Cloudwatch metrics section.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNo0kcFGtkBH-Fi6Vqx42Q.png" /><figcaption>The comparison graph of <strong>MemoryAllocation</strong> and <strong>MemoryUsage</strong> metrics.</figcaption></figure><p>That&#39;s it! The rest of it is basically the alarm configurations. The metric filters can be used for filtering many log outputs. You can simply log anything you want and create metrics over it. There are other options like filtering JSON outputs or text matches, etc.</p><p>Hope you enjoyed it, stay healthy! ✊</p><blockquote>Feel free to contact me on <a href="https://www.linkedin.com/in/tugay-ilik/">linkedin</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba7465a1776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How worker threads boosted my Node application]]></title>
            <link>https://levelup.gitconnected.com/how-worker-threads-boosted-my-node-application-9ff23abb8927?source=rss-22f4a898748b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff23abb8927</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Tugay İlik]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 10:45:48 GMT</pubDate>
            <atom:updated>2020-02-15T22:23:36.150Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>worker_threads</strong> module was released with Node.js <strong>v10.x LTS</strong> and stable with <strong>v13.x</strong>. It enables the use of threads that execute Javascript in <strong>parallel </strong>(be aware that parallelism and concurrency are close but different concepts)<em>.</em> It is very useful when the operations require <strong>CPU</strong> consumption.</p><p>In my application, I’m generating dynamic scripts per request with dynamic parameters. To generate the script, I’m running an npm command with <a href="https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options"><strong>execSync</strong></a><strong> </strong>command<strong>. </strong>I couldn’t use the async <a href="https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options"><strong>exec</strong></a> command because the command needs to follow a sequence for creating a dynamic script.</p><p>Let me show what was happening before the change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDLHHeM8jcrL8juHreSQnw.png" /><figcaption>draw.io</figcaption></figure><p>The process above was happening each time a request had been reaching our end from other microservices (AWS Lambda, Node.js). The whole process was sync until the 3rd step, only the upload was async. So the last step was not a thread blocker.</p><p>The incoming request amount per minute is around 30 to the generator service. That means for the instant generation process, a single process should finish in 2 seconds maximum, but mine was around 5–6 seconds. Thus, the application was locking the main thread until the active operations ends. That was delaying incoming generation processes sometimes up to 1 minute.</p><p>So, what have been changed after <strong>Worker Threads </strong>implementation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ly5Sr8apeluKe5v6Z8mh5w.png" /><figcaption>draw.io</figcaption></figure><p>In code, an example of worker threads looks like the following.</p><p>In the index.js file:</p><pre>// index.js<br>const { Worker } = require(&#39;worker_threads&#39;);</pre><pre>const workerData = {                <br>  write: { fileName: &#39;write.txt&#39;, filePath: &#39;./&#39; },<br>  read: { fileName: &#39;read.json&#39;, filePath: &#39;./&#39; },<br>  hash: Math.random(),            <br>};</pre><pre>new Worker(&#39;./worker.js&#39;, { workerData });</pre><p>In our worker.js file:</p><pre>// worker.js<br>const { readFileSync, appendFileSync, unlinkSync, existsSync } = require(&#39;fs&#39;);<br>const { resolve } = require(&#39;path&#39;);<br>const { workerData: { read, write, hash } } = require(&#39;worker_threads&#39;);</pre><pre>console.log(&#39;Process triggered.&#39;);<br>console.time(&#39;Execution time&#39;);</pre><pre>/**<br> * @return {Promise}<br> */<br>const sleep = async function () {<br>    return new Promise(resolve =&gt; {<br>        setTimeout(resolve, Math.floor(Math.random() * 5000) + 999);<br>    });<br>};</pre><pre>(async () =&gt; {<br>    // Act like process takes time<br>    await sleep();</pre><pre>    const writePath = resolve(write.filePath, write.fileName + &#39;-&#39; + hash);<br>    const readPath = resolve(read.filePath, read.fileName);<br>    const json = JSON.parse(readFileSync(readPath).toString(&#39;utf-8&#39;));</pre><pre>    // Remove the file before writing<br>    if (existsSync(writePath)) {<br>        unlinkSync(writePath);<br>    }</pre><pre>    json.forEach(item =&gt; {<br>        appendFileSync(writePath, JSON.stringify(item) + &#39;\n\n\n&#39;);<br>    });</pre><pre>    console.log(&#39;Process end.&#39;);<br>    console.timeEnd(&#39;Execution time&#39;);<br>})();</pre><p>With the implementation above, the application’s main thread is not busy with the generation process anymore. Each process is isolated and not a blocker for incoming processes. That dramatically decreases the delay in the generation process, <strong><em>but the CPU usage remained the same because workers are consuming a lot of CPU too.</em></strong></p><p>Because it made generation faster, it provided me other benefits too:</p><ul><li><strong><em>The read and write file processes got a lot faster </em></strong>🚀</li></ul><p>Since the main thread was always busy, the incoming read/write requests were delayed until it could find an empty slot in the execution queue. But now, it is happening immediately.</p><ul><li><strong><em>Response time decreased dramatically </em></strong>📉</li></ul><p>The application’s response time for static files served via express was around 3–5, sometimes 10 seconds until it had been cached. It took a lot of time until I realized what was going there. Serving static files with <strong>express</strong> is really fast unless you have a system that consumes CPU and has a really busy thread consumption. Static files are served by the <a href="https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options"><strong><em>readFile</em></strong></a> functionality of node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IoADRqU6j4oYdn1-Dbm7A.png" /><figcaption>metrics from dynatrace</figcaption></figure><p>The metrics show that the response time decreased after 16:00 (after deploying new version). Now, it is around <strong>100–200 milliseconds</strong> which is perfect.</p><p>I have enjoyed implementing <strong>worker_threads</strong> and seeing the perfect results 🕺.</p><p>I’ve created an example application for mocking how it looks on code.</p><p><a href="https://github.com/tugayilik/node-worker-threads">tugayilik/node-worker-threads</a></p><p>Hope you enjoyed while reading it! ✊</p><blockquote>Feel free to contact me on <a href="https://www.linkedin.com/in/tugay-ilik/">linkedin</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff23abb8927" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-worker-threads-boosted-my-node-application-9ff23abb8927">How worker threads boosted my Node application</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decreasing Webpack bundle size with conditional imports]]></title>
            <link>https://tugayilik.medium.com/decreasing-webpack-bundle-size-with-conditional-imports-f8bb94db8195?source=rss-22f4a898748b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8bb94db8195</guid>
            <category><![CDATA[bundle]]></category>
            <category><![CDATA[size]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Tugay İlik]]></dc:creator>
            <pubDate>Sun, 14 Jul 2019 16:48:14 GMT</pubDate>
            <atom:updated>2020-12-08T14:34:29.431Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decreasing Webpack’s bundle size with conditional imports</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8i6JERhI85CaSq57tIjnWw.png" /><figcaption>Image from <a href="https://webpack.js.org/">https://webpack.js.org/</a></figcaption></figure><p>There are several tools used for bundling JavaScript modules or assets. Most bundlers have tree shaking system which clears up unused modules before compiling the whole code and decreases bundle size accordingly. That is, it removes any code that isn’t actually used by your app.</p><p>But sometimes, even if you don’t use the functionality, you see that a library gets included in your output bundle anyway. You may need to load that item only for specific situations and not need it in your main bundle.</p><p>In those situations, you may look for dynamic module loading by setting a dynamic module import. But let&#39;s check what happens when we try to do that like below:</p><pre>const DynamicModule = import(`path/to/${dynamicModuleName}.js`)</pre><p>When you do that, Webpack imports each module inside the path/to/* path into your bundle and when your script evaluated on client side, it picks the required one and executes. Why does Webpack do that? Because it can’t know the value of the dynamicModuleName variable at build time.</p><p>Well, this can hurt our overall build. Let’s say you have a feature toggle set. Some of the features can be active or passive according to their status. You do not want that feature’s code when it’s passive.</p><p>On that point, webpack’s <a href="https://webpack.js.org/plugins/normal-module-replacement-plugin/"><strong><em>NormalModuleReplacementPlugin</em></strong></a> comes in handy. What it does is simply allow you to replace resources which match.</p><p>According to our scenario, the basic implementation will take those steps at below:</p><p>There should be a <strong>.empty.js </strong>(you can name it as whatever you want)<strong> </strong>file for your toggleable modules. That means if you have <strong>Module1</strong>, there should be also <strong>Module1.empty.js </strong>file too near the normal module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Su0_BaIoBMTrCXoPL7AbAQ.png" /></figure><p><em>Empty modules should be literally empty </em><strong><em>with only class exports,</em></strong><em> no methods, no variables, not dependencies. </em><strong><em>It may only contain some empty functions which is dependently used in another module</em></strong><em>.</em></p><p>For example, let’s say in <strong>ModuleX</strong> you import <strong>Module1</strong> and use <strong>Module1’s C method</strong>. In this case, when you load empty form of <strong>Module1</strong>, the application will throw an error on the client side since it does not have C method right? To fix that, you can simply create an empty method with exact name <em>— which is C in our case — </em>in <strong>Module1</strong>.</p><p>There should be a resolver file for the modules that can be marked as empty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d88a95f2da3c81d5c901033911dcdd3/href">https://medium.com/media/6d88a95f2da3c81d5c901033911dcdd3/href</a></iframe><p>We should tell the plugin, replace normal modules as empty modules according to their statuses</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3ba675868347e702495098d0fb0c2a4/href">https://medium.com/media/d3ba675868347e702495098d0fb0c2a4/href</a></iframe><p>In the last step in the webpack config, we have to activate our plugin like below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57b251fe7abb7e90b0a993ea5e8a3973/href">https://medium.com/media/57b251fe7abb7e90b0a993ea5e8a3973/href</a></iframe><p>Let’s import modules as normal ones and see the output according to their statuses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*_ppZN0xjTsNf0ZLVy9J4ig.png" /></figure><p>While both modules are marked as active</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*ltgsNxfaoMleVekLD_oupQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*hrWTvZayLs5DdA_fAlPDng.png" /></figure><p>While both modules are marked as passive;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*N2xRIku21RruwMO7vL8Pug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*SM3jXw18TW1CwIduQnjVig.png" /></figure><p>This technique dramatically decreases the bundle size no matter what. Not only those files, but also the unused modules inside the normal modules will be treeshaked and it may literally surprise you sometimes.</p><p>See the example repository for more clear understanding;</p><p><a href="https://github.com/tugayilik/decrease-webpack-bundle-sample">tugayilik/decrease-webpack-bundle-sample</a></p><p>I hope you had a chance to give a try to this approach! ✊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8bb94db8195" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Handling via Try & Catch Proxy in Javascript]]></title>
            <link>https://tugayilik.medium.com/error-handling-via-try-catch-proxy-in-javascript-54116dbf783f?source=rss-22f4a898748b------2</link>
            <guid isPermaLink="false">https://medium.com/p/54116dbf783f</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tugay İlik]]></dc:creator>
            <pubDate>Sat, 01 Dec 2018 22:07:27 GMT</pubDate>
            <atom:updated>2018-12-01T22:16:36.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*CbZRKFOXHyTCvmFrpRWbQg.png" /><figcaption>Simple javascript error</figcaption></figure><p>Errors can happen in any software. To keep your software/program working, you may want catch them, hide them or track them, or sometimes you want to give information to your clients when error happens, it’s up to you. But sometimes, those errors can’t be easy to catch. It can oblige you to wrap your code with several try catch blocks to preventing functionality loss. Adding those blocks brings more complexity, extra code logics and decreases your code cleanness.</p><p>Instead of doing this, you can wrap your class functions with a proxy.</p><p>Let’s get to work and understand how we can achieve this easily with a small proxy function!</p><p><strong>1.</strong>First, we define proxy function that takes an argument, which is the class that we are going to wrap its methods. In javascript, we can access all properties of a class over its prototype property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fba58d7025aa1243f910aaec38ab31c/href">https://medium.com/media/0fba58d7025aa1243f910aaec38ab31c/href</a></iframe><p><strong>2</strong>. If the class doesn’t have any property except constructor, we don’t need to wrap anything. Since constructor property is always exists on class creation we are handling this case too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7833787f6fb31272d07266cfcd92bd01/href">https://medium.com/media/7833787f6fb31272d07266cfcd92bd01/href</a></iframe><p><strong>3.</strong> It’s time to define our handler method for wrapping function executions. What it does, simply wraps given function with try catch block and calls it with given arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a44505b36e837b2e3df7eebee1de04ae/href">https://medium.com/media/a44505b36e837b2e3df7eebee1de04ae/href</a></iframe><p><strong>4.</strong> Now we have handler method. It’s time to wrap functions in given class with this wrapper function and override class functions with wrapped one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cbc6fc64d85ed4bbb008165ee0e1da9/href">https://medium.com/media/0cbc6fc64d85ed4bbb008165ee0e1da9/href</a></iframe><p>Object.getOwnPropertyDescriptors method returns a property descriptor for an own property (that is, one directly present on an object and not in the object’s prototype chain) of a given object. Via using this, we will access all properties of given super class. Then we will filter constructor and non-function properties. The rest will be overridden with wrapper function.</p><p><strong>6. </strong>That’s it, we are done! Now we can wrap our classes with our proxy helper;</p><pre>tryCatchProxy(MyClass);</pre><p>After doing this, method executions of super class, will be executed in wrapper function and if something goes wrong, it will be get into catch block! 🕺</p><p>Hope you enjoyed reading and it helps you ! ✴️</p><p>A working example can be found in this gist;</p><p><a href="https://gist.github.com/tugayilik/f574827ef31caf61b92de79b64dfa47e">https://gist.github.com/tugayilik/f574827ef31caf61b92de79b64dfa47e</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54116dbf783f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross Domain Data Unification With Javascript]]></title>
            <link>https://tugayilik.medium.com/cross-domain-data-unification-with-javascript-befaff5b742f?source=rss-22f4a898748b------2</link>
            <guid isPermaLink="false">https://medium.com/p/befaff5b742f</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tugay İlik]]></dc:creator>
            <pubDate>Sun, 01 Oct 2017 07:35:30 GMT</pubDate>
            <atom:updated>2023-12-20T10:42:32.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*lTfQoqCm7m8FxZMshJ5VRQ.png" /></figure><h3><strong><em>THIS METHOD IS NO LONGER VALID FOR CROSS DOMAINS BUT STILL VALID FOR SUBDOMAINS. IT IS BECAUSE SOME PRIVACY CONCERNS CAUSED DATA STORAGE PARTITIONING IN THE BROWSERS.</em></strong></h3><p>For further reading -&gt; <a href="https://developers.google.com/privacy-sandbox/3pcd/storage-partitioning">https://developers.google.com/privacy-sandbox/3pcd/storage-partitioning</a></p><p>You might be thinking, how can you share data between different domains.</p><p>In this small tutorial I’m going to explain, how can this be achievable by only using javascript.</p><p>I will demonstrate this with user id example. We will generate a user id and we will share it between two domains.</p><p>Let’s get started!</p><p>First of all we need two different domains and a helper frame which served as iframe on both websites. This will be a layer for communicating between websites. We will use <strong><em>postMessage</em></strong><em> </em>for communication between frames, and <strong><em>localStorage</em></strong> for storing data.</p><p>Let’s create small integration script to integrate our helper frame. You can simply create an empty helper.html file. We will fill it soon. Insert the script below to <strong>both</strong> websites body.</p><pre>&lt;script type=&#39;text/javascript&#39;&gt;<br>  (function (){<br>     var helperFrame = document.createElement(&#39;iframe&#39;);<br>     helperFrame.src = &#39;//api.example.dev/helper.html&#39;;<br>     helperFrame.id = &#39;helperFrame&#39;;<br>     helperFrame.style = &#39;display:none;&#39;;<br>     var body = document.getElementsByTagName(&#39;body&#39;)[0];<br>     body.appendChild(helperFrame);<br>   })();<br>&lt;/script&gt;</pre><p>Next we will define our functions <strong>inside helper.html</strong> to get and set user id. We will use local storage to manage user id.</p><pre>// Those callback functions will be triggered from parent frame.<br>let callbacks = {<br>  setUserId: () =&gt; {<br>    if (localStorage.getItem(&#39;userId&#39;) === null) { <br>      // Generate random userId and store it in local storage<br>      localStorage.setItem(&#39;userId&#39;, Math.random().toString().substr(2));<br>    }<br>  }, <br>  getUserId: () =&gt; {<br>    // Send user id to parent frame when its called.<br>    window.parent.postMessage(localStorage.getItem(&#39;userId&#39;),  &#39;*&#39;) <br>  }<br>}</pre><pre>// Set User Id by default when frame loaded<br>// It can be triggered from parent frame also<br>callbacks.setUserId();</pre><p>Now via using window.postMessage function, we will communicate with helper frame from parent frame. For doing this, there must be message capturing event on both sides because we will set userId from parent frame and we get userId from helper frame. Let’s define it.</p><p>In <strong>helper.html, </strong>define eventListener for listening postMessage events. The event argument returns the postMessage information. It has data property which is the message data. In our demonstration we are going to use function names as data for calling our callback functions from parent frame.</p><pre>window.addEventListener(&#39;message&#39;, (event) =&gt; {<br>   callbacks[event.data]();<br>});</pre><p>We are done with helper.html. Now it’s time to define listeners and calling function from parent frame.</p><pre><br>window.onload = () =&gt; {</pre><pre>  // Defining helper frame&#39;s window object.<br>  let helperFrameWindow = document.getElementById(&#39;helperFrame&#39;).contentWindow;<br>   <br>   let getUserId = () =&gt; () {<br>     // Sending post message to read data from helper frame<br>     helperFrameWindow.postMessage(&#39;getUserId&#39;, &#39;*&#39;);<br>   }</pre><pre>  // Capture incoming messages from helper frame<br>  window.addEventListener(&#39;message&#39;, (event) =&gt; {<br>    console.log(&#39;User Id From helper frame:&#39; + event.data);<br>  });</pre><pre>  getUserId();<br>}</pre><p>If I inspect chrome console and local storage, I should be seeing something like the below. That means on <strong>unification1.dev:3001</strong> website, I have my helper frame set and have userId on its local storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*3D_N6P-E37bFDbx8njLDfg.png" /></figure><p>If I inspect my other website which is <strong>unification2.dev:3002</strong>, I should be seeing same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*n0ZXVC5YlFepqDJs_RAdUA.png" /></figure><p>And thats it! I can access same userId on both websites and <strong>target my user.</strong></p><blockquote>Example code exists in github.</blockquote><blockquote><a href="https://github.com/tugayilik/unification/tree/75c65ae930fa64f5497d0f5c67bd79ef0245e97d">https://github.com/tugayilik/unification/tree/75c65ae930fa64f5497d0f5c67bd79ef0245e97d</a></blockquote><p>Thanks for your time, hope you enjoyed it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=befaff5b742f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>