<?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 Mladen Bolic on Medium]]></title>
        <description><![CDATA[Stories by Mladen Bolic on Medium]]></description>
        <link>https://medium.com/@mladen.bolic?source=rss-313bdd56b73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yvZL_3NhbNGGfWRt.</url>
            <title>Stories by Mladen Bolic on Medium</title>
            <link>https://medium.com/@mladen.bolic?source=rss-313bdd56b73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:09:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mladen.bolic/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[SSR with Vue.js (Part 4) — Setting Up Open Graph Meta Tags with SSR]]></title>
            <link>https://medium.com/@mladen.bolic/ssr-with-vue-js-part-4-setting-up-open-graph-meta-tags-with-ssr-dc4370b542c5?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc4370b542c5</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[open-graph]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 12:34:14 GMT</pubDate>
            <atom:updated>2025-02-12T07:08:23.884Z</atom:updated>
            <content:encoded><![CDATA[<h3>SSR with Vue.js (Part 4) — Setting Up Open Graph Meta Tags with SSR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*4E4fMpDpWRe_naJG.jpeg" /></figure><p>This is the last in the series of articles on how to se up SSR with Vue.js.</p><ul><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-1-1d860a27cdfb">SSR with Vue.js (Part 1)</a></li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-2-set-up-state-management-with-ssr-5427d65d3cfb">SSR with Vue.js (Part 2) — Setting Up State Management with SSR</a></li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-3-set-up-vue-router-with-ssr-a9e7fde9e089">SSR with Vue.js (Part 3) — Setting Up Vue Router with SSR</a></li><li>SSR with Vue.js (Part 4) — Setting Up Open Graph Meta Tags with SSR</li></ul><h3><em>What are Open Graph meta tags?</em></h3><p>Open Graph meta tags are HTML tags that control how URLs are displayed when shared on social media platforms.</p><p>To make Open Graph meta tags work in Single Page Applications (SPAs), we need to set up proper server-side rendering (SSR) and configure the correct meta tags for each application page.</p><p>For setting up Open Graph meta tags, we will use the <a href="https://unhead.unjs.io/">Unhead</a> library.</p><p>Let’s first introduce the Unhead library into our project, and then we’ll dive into the specific server-side configurations required to render meta tags for our pages.</p><p>This is the final part of our SSR with Vue.js series, so we will build upon <a href="https://github.com/mladenbolic/vue-ssr/tree/vue-ssr-part-3">the code from our previous article</a>.</p><h3>Unhead Setup</h3><p>First, lets install Unhead and make it work on our client-side code.</p><pre>$npm i @unhead/vue</pre><p>Now open the main.js file and register Unhead as a Vue plugin.</p><pre>const head = createHead()<br>app.use(head)</pre><p>Once the Unhead plugin is set up, we can use its useHead() function to specify the content of the &lt;head /&gt; tag. Let&#39;s go ahead and do that.</p><p>Let’s start by opening our Home page and adding several Open Graph meta tags to the page header: og:title, og:description, og:url, and og:image.</p><pre>import { useHead } from &quot;@unhead/vue&quot;;<br><br>useHead({<br>  title: &quot;Home Page&quot;,<br>  meta: [<br>    {<br>      key: &quot;og:title&quot;,<br>      property: &quot;og:title&quot;,<br>      content: &quot;Home Page&quot;,<br>    },<br>    {<br>      key: &quot;og:description&quot;,<br>      property: &quot;og:description&quot;,<br>      content:<br>        &quot;Home page for Open Graph meta tag setup for Vue SSR application.&quot;,<br>    },<br>    { key: &quot;og:url&quot;, property: &quot;og:url&quot;, content: &quot;https://sixhours.io&quot; },<br>    {<br>      key: &quot;og:image&quot;,<br>      property: &quot;og:image&quot;,<br>      content: require(&quot;@/assets/home.png&quot;),<br>    },<br>    { key: &quot;og:image:width&quot;, property: &quot;og:image:width&quot;, content: &quot;1200&quot; },<br>    { key: &quot;og:image:height&quot;, property: &quot;og:image:height&quot;, content: &quot;630&quot; },<br>  ],<br>});</pre><p>We’ll do the same thing for the About page.</p><pre>import { useHead } from &quot;@unhead/vue&quot;;<br><br>useHead({<br>  title: &quot;About Page&quot;,<br>  meta: [<br>    {<br>      key: &quot;og:title&quot;,<br>      property: &quot;og:title&quot;,<br>      content: &quot;About Page&quot;,<br>    },<br>    {<br>      key: &quot;og:description&quot;,<br>      property: &quot;og:description&quot;,<br>      content:<br>        &quot;About page for Open Graph meta tag setup for Vue SSR application.&quot;,<br>    },<br>    { key: &quot;og:url&quot;, property: &quot;og:url&quot;, content: &quot;https://sixhours.io&quot; },<br>    {<br>      key: &quot;og:image&quot;,<br>      property: &quot;og:image&quot;,<br>      content: require(&quot;@/assets/about.png&quot;),<br>    },<br>    { key: &quot;og:image:width&quot;, property: &quot;og:image:width&quot;, content: &quot;1200&quot; },<br>    { key: &quot;og:image:height&quot;, property: &quot;og:image:height&quot;, content: &quot;630&quot; },<br>  ],<br>});</pre><p>Now if we run the development server with $npm run server and open the <a href="http://localhost:8082/">http://localhost:8082</a> in the browser, we’ll see that Unhead has appended the Open Graph meta tags to both of our pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*o9VgzM7ePUORvfQjQ41GXw.png" /><figcaption>Home page OpenGraph meta tags</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*P4Cjtr38u_xBe-WGrvsnuQ.png" /><figcaption>About page OpenGraph meta tags</figcaption></figure><p>One caveat with this current solution is that setting meta tags only works on the client-side. When sharing the page, the HTML we get from the server response does not contain any meta tags. Only once the page is downloaded and hydrated on the client-side, the client-side code is going to execute and generate the meta tags.</p><p>This means that when sharing the URL in chat apps or social media platforms, the title, description, URL, and image will not appear on a page preview.</p><p>But how can we set meta tags on server-side as well?</p><p>First we need to register the Unhead plugin in main.server.js, just like we did for the client-side code.</p><pre>const head = createHead();<br>app.use(head);</pre><p>Next, we’ll install Unhead support for rendering head tags within the server-side code.</p><pre>$npm i @unhead/ssr</pre><p>Once Unhead SSR is installed, we can use the renderSSRHead() function to retrieve the generated head tags for a page.</p><pre>const { headTags: meta } = await renderSSRHead(head);<br><br>// return application content, state and meta tags for server side rendering<br>return { content, state, meta };</pre><p>Now we have all the necessary data to render HTML page with Open Graph head tags on our server.</p><p>So, before finalizing the setup, let’s update the Express server and make it return a page HTML with generated head tags.</p><h3>Setting Express Server</h3><p>Instead of manually generating HTML on the server side, we’ll use index.html as a template. This file is generated during the application build process.</p><p>If we open the /dist/client/index.html file, we’ll see that the Webpack build has already inserted the necessary &lt;script&gt; and &lt;link&gt; tags. The only thing we need to do is to add the meta tags within the &lt;head&gt; element and inject the server-side generated application code into the &lt;div id=&quot;app&quot;/&gt; container.</p><pre>&lt;!-- index.html--&gt;<br>&lt;!doctype html&gt;<br>&lt;html lang=&quot;&quot;&gt;<br><br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width,initial-scale=1&quot;&gt;<br>    &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot;&gt;<br>    &lt;title&gt;vue-ssr-delete&lt;/title&gt;<br>    &lt;script defer=&quot;defer&quot; src=&quot;/js/chunk-vendors.9452e265.js&quot;&gt;&lt;/script&gt;<br>    &lt;script defer=&quot;defer&quot; src=&quot;/js/app.43aa8d53.js&quot;&gt;&lt;/script&gt;<br>    &lt;link href=&quot;/css/app.40f00746.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;&lt;noscript&gt;&lt;strong&gt;We&#39;re sorry but vue-ssr-delete doesn&#39;t work properly without JavaScript enabled. Please enable<br>            it to continue.&lt;/strong&gt;&lt;/noscript&gt;<br>    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>Ok, let’s implement the changes mentioned above. First, we’ll read the index.html template file and then replace the &lt;div id=&quot;app&quot;/&gt; container with the server-generated code.</p><pre>  fs.readFile(path.join(__dirname, distPath, &quot;index.html&quot;), (err, html) =&gt; {<br>    if (err) {<br>      throw err;<br>    }<br><br>    // eslint-disable-next-line no-param-reassign<br>    html = html<br>      .toString()<br>      .replace(<br>        &#39;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;&#39;,<br>        `${renderState}&lt;div id=&quot;app&quot;&gt;${content}&lt;/div&gt;`<br>      )<br>    res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);<br>    res.send(html);<br>  });</pre><p>Next, we’ll get the meta tags from the render app and insert them into the &lt;head&gt; element.</p><pre>const { content, state, meta } = await renderApp(req.url);<br><br>...<br><br>fs.readFile(path.join(__dirname, distPath, &quot;index.html&quot;), (err, html) =&gt; {<br>  if (err) {<br>    throw err;<br>  }<br><br>  // eslint-disable-next-line no-param-reassign<br>  html = html<br>    .toString()<br>    .replace(<br>      &#39;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;&#39;,<br>      `${renderState}&lt;div id=&quot;app&quot;&gt;${content}&lt;/div&gt;`<br>    )<br>    .replace(&quot;&lt;/head&gt;&quot;, `${meta || &quot;&quot;}&lt;/head&gt;`)<br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);<br>  res.send(html);<br>});</pre><p>Ok, we are almost there, but there’s one more thing we need to address.</p><p>The application that will display our page preview doesn’t know how to resolve absolute paths used for our Open Graph image URLs (e.g., /img/about.43aa8d53.png). We need to prepend the base URL (with the domain and port) to the image path, such as: <a href="https://sixhours.io/img/about.43aa8d53.png.">https://sixhours.io/img/about.43aa8d53.png</a>.</p><p>To solve this, we’ll extract the fullUrland baseUrl from the request. We will prepend the baseUrl to all static image URLs, and the full URL will be used for specifying the Open Graph URL i.e. the URL of the page we are sharing.</p><pre>const { content, state, meta } = await renderApp(req.url);<br><br>const baseUrl = req.protocol + &quot;://&quot; + req.get(&quot;host&quot;);<br>const fullUrl = baseUrl + req.originalUrl.split(/[?#]/)[0];<br><br>const renderState = `<br>&lt;script&gt;<br>  window.__INITIAL_STATE__ = ${serialize(state)}<br>&lt;/script&gt;`;<br><br>fs.readFile(path.join(__dirname, distPath, &quot;index.html&quot;), (err, html) =&gt; {<br>  if (err) {<br>    throw err;<br>  }<br><br>  // eslint-disable-next-line no-param-reassign<br>  html = html<br>    .toString()<br>    .replace(<br>      &#39;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;&#39;,<br>      `${renderState}&lt;div id=&quot;app&quot;&gt;${content}&lt;/div&gt;`<br>    )<br>    .replace(&quot;&lt;/head&gt;&quot;, `${meta || &quot;&quot;}&lt;/head&gt;`)<br>    .replace(<br>      &#39;&lt;meta property=&quot;og:url&quot; content=&quot;https://sixhours.io&quot;&gt;&#39;,<br>      `&lt;meta property=&quot;og:url&quot; content=&quot;${fullUrl}&quot;&gt;`<br>    )<br>    .replace(/content=&quot;\/img\//g, `content=&quot;${baseUrl}/img/`);<br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);<br>  res.send(html);<br>}); </pre><p><em>Even though most of share previews should work without without specifying full url for images, we are going to use full urls here with specified protocol and domain for image urls.</em></p><p>Now, let’s build the application, start the server, and verify that the Open Graph meta tags are properly set on the server.</p><pre>$npm run build &amp;&amp; node server.js</pre><p>Once the server is running, open the browser and navigate to http://localhost:8083/. In the web console, you should see that the response includes the index.html content with the correctly generated Open Graph meta tags for the Home page. If you visit http://localhost:8083/about, you should see the About page HTML response with its own meta tags.</p><p>Great!! Now we have a fully functional SSR app, with URLs ready for sharing 😊.</p><p><em>In order to test the app we can use something like </em><a href="https://ngrok.com/"><em>Ngrok</em></a><em> to make our app publicly available over Internet. We just need to map our running app’s port (8083) to Ngroks publicly available address.</em></p><p><em>If we now open our favourite chat app and share Home and About pages, we will see that the page preview, with title, description and image will be generated correctly.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*USTKc8tjebDMlZhYjApfCQ.png" /><figcaption>Home page share preview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*_HpcCLvDxuOdZZaLtvFgaA.png" /><figcaption>About page share preview</figcaption></figure><p>Additionally, several sharing debuggers, like <a href="https://www.opengraph.xyz/">Open Graph Preview</a> or <a href="https://debug.iframely.com/">Iframely</a> are available for testing meta tags settings. These tools allow you to check the meta tags and preview how your website URL will appear on different social media platforms.</p><p>And that’s it for setting up Open Graph in an SSR app!! You can find the final code on <a href="https://github.com/mladenbolic/vue-ssr/tree/vue-ssr-part-4">Github</a>. Enjoy sharing your applications!! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc4370b542c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSR with Vue.js (Part 3) — Set up Vue Router with SSR]]></title>
            <link>https://medium.com/@mladen.bolic/ssr-with-vue-js-part-3-set-up-vue-router-with-ssr-a9e7fde9e089?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e7fde9e089</guid>
            <category><![CDATA[vue-router]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 11:39:00 GMT</pubDate>
            <atom:updated>2025-02-12T07:22:02.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>SSR with Vue.js (Part 3) — Setting Up Vue Router with SSR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JvrmqaD1OxhWuECUlijLOA.jpeg" /></figure><p>This is the third in the series of articles on how to set up SSR with Vue.js.</p><ul><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-1-1d860a27cdfb">SSR with Vue.js (Part 1)</a></li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-2-set-up-state-management-with-ssr-5427d65d3cfb">SSR with Vue.js (Part 2) — Setting Up State Management with SSR</a></li><li>SSR with Vue.js (Part 3) — Setting Up Vue Router with SSR</li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-4-setting-up-open-graph-meta-tags-with-ssr-dc4370b542c5">SSR with Vue.js (Part 4) — Setting Up Open Graph Meta Tags with SSR</a></li></ul><p>In <a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-2-set-up-state-management-with-ssr-5427d65d3cfb">the previous article</a> we covered setting up state management for SSR in a Vue.js application. In this section, we’ll focus on configuring routing and integrating <a href="https://router.vuejs.org/">Vue Router</a> with SSR.</p><p>We will continue from the <a href="https://github.com/mladenbolic/vue-ssr/tree/vue-ssr-part-2">code base we built in Part 2</a> and expand it in order to introduce <a href="https://router.vuejs.org/">Vue Router</a> in our SSR app.</p><h3>Vue Router Setup</h3><p>Vue Router is the official routing library for Vue.js, designed for handling client-side navigation in Single Page Applications (SPAs). In SPAs, there’s no concept of multiple HTML pages, everything is loaded through a single index.html. So, how do we manage navigation and browser history? This is where Vue Router comes in. It allows us to reflect page changes in the browser&#39;s URL.</p><p>But what about server-side routing? For example, when we visit http://localhost:8083/about, our server should respond with the HTML content for the About page, not the Home (index) page. Let’s see how we can achieve this with Vue Router in an SSR setup.</p><p>First, let’s add Vue Router to our existing SSR app.</p><pre>$npm install vue-router@4</pre><p>Once the router is installed, we’ll create two additional pages for our app: Home page and About page. For full pages code, please check the <a href="https://github.com/mladzo/vue-ssr/tree/vue-ssr-part-3">Github</a>.</p><p>Now, let’s modify App.js to incorporate the RouterLink and RouterView components. The RouterView component is where Vue Router will render the content of the current page.</p><pre>&lt;template&gt;<br>  &lt;nav&gt;<br>    &lt;router-link to=&quot;/&quot;&gt;Home&lt;/router-link&gt; |<br>    &lt;router-link to=&quot;/about&quot;&gt;About&lt;/router-link&gt;<br>  &lt;/nav&gt;<br>  &lt;router-view /&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  name: &quot;App&quot;,<br>  components: {},<br>};<br>&lt;/script&gt;<br><br>&lt;style&gt;<br>#app {<br>  font-family: Avenir, Helvetica, Arial, sans-serif;<br>  -webkit-font-smoothing: antialiased;<br>  -moz-osx-font-smoothing: grayscale;<br>  text-align: center;<br>  color: #2c3e50;<br>  margin-top: 60px;<br>}<br>&lt;/style&gt;</pre><p>Next, let’s set up a simple Vue Router with some initial routes.</p><p>In the src folder create ./router/index.js file with the following content:</p><pre>import {<br>  createRouter as createVueRouter,<br>  createMemoryHistory,<br>  createWebHistory,<br>} from &quot;vue-router&quot;;<br>import HomePage from &quot;@/pages/HomePage.vue&quot;;<br>import AboutPage from &quot;@/pages/AboutPage.vue&quot;;<br><br>const routes = [<br>  {<br>    path: &quot;/&quot;,<br>    name: &quot;home&quot;,<br>    component: HomePage,<br>  },<br>  {<br>    path: &quot;/about&quot;,<br>    name: &quot;about&quot;,<br>    component: AboutPage,<br>  },<br>];<br><br>const isServer = typeof window === &quot;undefined&quot;;<br><br>const createRouter = () =&gt;<br>  createVueRouter({<br>    history: isServer<br>      ? createMemoryHistory()<br>      : createWebHistory(process.env.BASE_URL),<br>    routes,<br>  });<br><br>export default createRouter;</pre><p><em>For SSR we will use </em><em>createMemoryHistory and for client-side routing we will use </em><em>createWebHistory.</em></p><p>Just like with the store, we’ll create and return a function that initializes the router.</p><p>Once the router is created, we need to include it as a plugin in our app. To do this, open main.js and introduce the necessary changes.</p><pre>import { createApp } from &quot;vue&quot;;<br>import App from &quot;./App.vue&quot;;<br>import createStore from &quot;./store&quot;;<br>import createRouter from &quot;./router&quot;;<br><br>const store = createStore();<br>const router = createRouter();<br><br>// initialize the store with server-initialized state.<br>// the state is determined during SSR and inlined in the page markup.<br>if (window &amp;&amp; window.__INITIAL_STATE__) {<br>  store.state.value = window.__INITIAL_STATE__;<br>}<br><br>createApp(App).use(store).use(router).mount(&quot;#app&quot;, true);</pre><p>Similar changes should be done in main.server.js.</p><pre>import { createSSRApp } from &quot;vue&quot;;<br>import App from &quot;./App.vue&quot;;<br>import { renderToString } from &quot;@vue/server-renderer&quot;;<br>import createStore from &quot;./store&quot;;<br>import createRouter from &quot;./router&quot;;<br><br>export default async (url) =&gt; {<br>  console.log(&quot;url=&quot;, url);<br>  const app = createSSRApp(App);<br><br>  const store = createStore();<br>  const router = createRouter();<br><br>  app.use(store);<br>  app.use(router);<br><br>  const context = {};<br>  const content = await renderToString(app, context);<br>  const state = store.state.value;<br><br>  // return application content and state for server-side rendering<br>  return { content, state };<br>};</pre><p>At this point, our router on server-side does not do much, we are not using url passed in the request, and we’re returning the index.html page on each request. Let’s fix that.</p><p>In SSR, we need to handle routing by ourself. When we receive a request for a specific URL, we need to pass that URL to the router and render the corresponding page content. If the page URL doesn’t exist, we’ll return a 404 error.</p><pre>// set server-side router&#39;s location<br>// On page refresh router isReady() resolves immediately, but current path is still not<br>// available as a matched component (previous path is still matched) so we need to wait until push<br>// promise resolves<br>try {<br>  await router.push(url);<br>  await router.isReady();<br>} catch (err) {<br>  throw new Error(err);<br>}<br><br>const matchedComponents = router.currentRoute.value.matched;<br><br>if (!matchedComponents.length) {<br>  throw new Error(&quot;404&quot;);<br>}</pre><p>Now, let’s build the application, start the server, and check if the configuration works.</p><pre>$npm run build &amp;&amp; node server.js</pre><p>Now if we open the browser and go to <a href="http://localhost:8083/">http://localhost:8083/</a> we should see in the web console that the Home page HTML is being returned as response. If we open <a href="http://localhost:8083/about,">http://localhost:8083/about</a> in the browser, the server should return the HTML for the About page.</p><h3>Conclusion</h3><p>That’s it for this part!! We’ve now set up basic routing with Vue Router for our SSR app. You can find the full code on <a href="https://github.com/mladenbolic/vue-ssr/tree/vue-ssr-part-3">Github</a>.</p><p>In <a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-4-setting-up-open-graph-meta-tags-with-ssr-dc4370b542c5">the next article</a>, we’ll explore how to set up OpenGraph meta tags for Vue SSR application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e7fde9e089" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSR with Vue.js (Part 2) — Set up State Management with SSR]]></title>
            <link>https://medium.com/@mladen.bolic/ssr-with-vue-js-part-2-set-up-state-management-with-ssr-5427d65d3cfb?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/5427d65d3cfb</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 07:40:02 GMT</pubDate>
            <atom:updated>2025-02-13T20:09:16.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>SSR with Vue.js (Part 2) — Setting Up State Management with SSR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*FFqZ1ZHksTASjvlV" /></figure><p>This is 2nd in the series of articles on how to se up SSR with Vue.js.</p><ul><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-1-1d860a27cdfb">SSR with Vue.js (Part 1)</a></li><li>SSR with Vue.js (Part 2) — Setting Up State Management with SSR</li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-3-set-up-vue-router-with-ssr-a9e7fde9e089">SSR with Vue.js (Part 3) — Setting Up Vue Router with SSR</a></li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-4-setting-up-open-graph-meta-tags-with-ssr-dc4370b542c5">SSR with Vue.js (Part 4) — Setting Up Open Graph Meta Tags with SSR</a></li></ul><p>In <a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-1-1d860a27cdfb">the previous article</a> we explored how to make the initial setup of the Vue SSR application. In this article we will walk through setting up a state management library and integrating Server-side rendering with <a href="https://pinia.vuejs.org/">Pinia</a>.</p><p>Before jumping to the state management setup, we will tweak our Webpack build configuration.</p><p>We will continue with our <a href="https://github.com/mladenbolic/vue-ssr/tree/vue-ssr-part-1">code from Part 1</a> and build upon by introducing <a href="https://pinia.vuejs.org/">Pinia state management library</a> to our app.</p><h3><strong>Build Configuration</strong></h3><p>The idea is to introduce two builds for our application. Client-side build i.e. code that will run on client and server-side build i.e. code that will run on server. Both builds will be located within /dist folder.</p><p>Ok, first let’s modify our package.json file and reshape the build script.</p><p>First, we will create separate build:client and build:server run scripts that will be responsible for running client-side and server-side build for our project.</p><pre>&quot;build&quot;: &quot;rm -rf ./dist &amp;&amp; npm run build:client &amp;&amp; npm run build:server&quot;,<br>&quot;build:client&quot;: &quot;vue-cli-service build --dest dist/client&quot;,<br>&quot;build:server&quot;: &quot;SSR=1 vue-cli-service build --dest dist/server&quot;,</pre><p>Next, instead of relying on the default Vue Webpack build configuration for the client, we will introduce the manifest plugin to specify the output location for the client-side manifest file.</p><pre>if (!process.env.SSR) {<br>  config<br>    .plugin(&quot;manifest&quot;)<br>    .use(new WebpackManifestPlugin({ fileName: &quot;client-manifest.json&quot; }));<br><br>  config.entry(&quot;app&quot;).clear().add(&quot;./src/main.js&quot;);<br>  return;<br>}</pre><p>The server-side build configuration code, should stay the same.</p><h3>Pinia Setup</h3><p>First, we are going to configure Pinia store for the client-side. Once that is done, we will set it up for SSR as well.</p><p>First, lets add Pinia to our existing app.</p><pre>$npm i pinia </pre><p>Now, we are going to set up simple Pinia store with some initial state.</p><p>Under the src folder create ./store/index.js with the following content:</p><pre>import { defineStore, createPinia } from &quot;pinia&quot;;<br><br>export const useCounterStore = defineStore(&#39;counter&#39;, {<br>  state: () =&gt; ({ count: 0 }),<br>  getters: {<br>    double: state =&gt; state.count * 2,<br>  },<br>  actions: {<br>    increment() {<br>      this.count++<br>    },<br>    reset() {<br>      this.count = 0;<br>    },<br>  },<br>});<br><br>const createStore = () =&gt; createPinia();<br><br>export default createStore;</pre><p>When store is created we should include it to our app as a plugin. Let’s open the main.js file and include the root store to our app.</p><pre>import { createApp } from &quot;vue&quot;;<br>import App from &quot;./App.vue&quot;;<br>import createStore from &quot;./store&quot;;<br><br>const store = createStore();<br><br>createApp(App).use(store).mount(&quot;#app&quot;);</pre><p>To verify that everything is working ok, we should create at least one component that is using given store. Ok, let’s do that.</p><p>Under /src/components folder create a new component Counter.vue and let’s introduce counter store to it.</p><pre>&lt;template&gt;<br>  &lt;div&gt;Counter: {{ store.count }}&lt;/div&gt;<br>  &lt;button @click=&quot;store.increment()&quot;&gt;Increment&lt;/button&gt;<br>  &lt;button @click=&quot;store.reset()&quot; style&gt;Reset&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { useCounterStore } from &quot;../store&quot;;<br><br>const store = useCounterStore();<br>&lt;/script&gt;<br><br>&lt;style scoped&gt;<br>button {<br>  margin-left: 5px;<br>}<br>button:last-child {<br>  margin-left: none;<br>}<br>&lt;/style&gt;</pre><p><em>Note that we are using </em><a href="https://vuejs.org/api/sfc-spec.html#script-setup"><em>Single-File Components</em></a><em> here which provides us, among other benefits, better code runtime performance.</em></p><p>Now, let’s add the Counter component to our main App.vue file</p><pre>&lt;template&gt;<br>  &lt;img alt=&quot;Vue logo&quot; src=&quot;./assets/logo.png&quot; /&gt;<br>  &lt;Counter /&gt;<br>  &lt;HelloWorld msg=&quot;Welcome to Your Vue.js App&quot; /&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import HelloWorld from &quot;./components/HelloWorld.vue&quot;;<br>import Counter from &quot;./components/Counter.vue&quot;;<br><br>export default {<br>  name: &quot;App&quot;,<br>  components: {<br>    HelloWorld,<br>    Counter,<br>  },<br>};<br>&lt;/script&gt;</pre><p>and start the dev server.</p><pre>$npm run serve</pre><p>Once the dev server is up and running, we should visit <a href="http://localhost:8082/">http://localhost:8082/</a> in the browser. If everything is ok, we should see the initial counter value together with “Increment” and “Reset” buttons. If we click “Increment” global counter state should increment it’s value, if we click “Reset” global state should be set to 0.</p><p>Ok, now when client-side state management is set up, let’s set the server-side state management.</p><h3>SSR State Management</h3><p><em>Creating stores with Pinia should work out of the box for SSR as long as you call your </em><em>useStore() functions at the top of </em><em>setup functions.</em></p><p>For server-side state managment we will do a similar thing we did when we were setting the client-side code. We will change main.server.js file a bit and instead of exporting app itself as a default value, we will introduce and export an async function which will be responsible for initializing the app and its plugins for the server side rendering.</p><pre>import { createSSRApp } from &quot;vue&quot;;<br>import App from &quot;./App.vue&quot;;<br>import createStore from &quot;./store&quot;;<br>import { renderToString } from &quot;@vue/server-renderer&quot;;<br><br>export default async (url) =&gt; {<br>  console.log(&quot;url=&quot;, url);<br><br>  const app = createSSRApp(App);<br><br>  const store = createStore();<br><br>  app.use(store);<br><br>  const context = {};<br>  const content = await renderToString(app, context);<br>  const state = store.state.value;<br><br>  // return application content and state for server side rendering<br>  return { content, state };<br>};</pre><p><em>There is an important reason why we took this approach and that is cross-request state pollution. Creating a new instance of the entire application, including the router and global stores, on each server request will protect us not to accidentally leak the state between different requests.</em></p><p>Since we are now rendering application HTML content in the main.server.js application file, we should remove renderToString() from the server.js file.</p><pre>const express = require(&quot;express&quot;);<br>const path = require(&quot;path&quot;);<br>const manifest = require(path.join(__dirname, &quot;./dist/server/ssr-manifest.json&quot;));<br><br>const server = express();<br><br>const distPath = &quot;./dist/server&quot;;<br>server.use(&quot;/img&quot;, express.static(path.join(__dirname, distPath, &quot;img&quot;)));<br>server.use(&quot;/js&quot;, express.static(path.join(__dirname, distPath, &quot;js&quot;)));<br>server.use(&quot;/css&quot;, express.static(path.join(__dirname, distPath, &quot;css&quot;)));<br>server.use(<br>  &quot;/favicon.ico&quot;,<br>  express.static(path.join(__dirname, distPath, &quot;favicon.ico&quot;))<br>);<br><br>const appPath = path.join(__dirname, &quot;./dist/server&quot;, manifest[&quot;app.js&quot;]);<br>const renderApp = require(appPath).default;<br><br>// handle all routes in our application<br>server.get(&quot;*&quot;, async (req, res) =&gt; {<br>  const { content, state } = await renderApp(req.url);<br><br>  console.log(state);<br><br>  const html = `&lt;html&gt;<br>      &lt;head&gt;&lt;title&gt;Vue SSR&lt;/title&gt;<br>      &lt;link rel=&quot;stylesheet&quot; href=&quot;${manifest[&quot;app.css&quot;]}&quot; /&gt;<br>      &lt;/head&gt;<br>      &lt;body&gt;&lt;div id=&quot;app&quot;&gt;${content}&lt;/div&gt;&lt;/body&gt;<br>      &lt;/html&gt;`;<br><br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);<br>  res.send(html);<br>});<br><br>server.listen(8083);<br><br>console.log(`Running on http://localhost:8083`);</pre><p>We are now importing async function from our application not the application itself. This function takes one argument, request url and returns application content and state. For now, we will just log the state to the console.</p><p>If we now build and restart the server and open <a href="http://localhost:8083/,">http://localhost:8083/</a> in the browser, we should see counter state in the server log.</p><pre>$npm run build &amp;&amp; node server.js</pre><p>But we are not finished yet. We can access the state on our web server, but we should be able to set the initial state for our application as well. So, how can we do that?</p><p>In order to set up the initial state on the server-side, we can serialize the current app state and use window object to make it globally available for the client-side code.</p><p>Since we are seralizing the store which can contain regexps, dates, maps, we will use serialize-javascript library for serialization. So, let’s install the libraray.</p><pre>$npm i -D serialize-javascript</pre><p>Now, we will serialize the state data and attach it to the window.__INITIAL_STATE__ global variable .</p><pre>const serialize = require(&quot;serialize-javascript&quot;);<br>...<br>const renderState = `<br>   &lt;script&gt;<br>     window.__INITIAL_STATE__ = ${serialize(state)}<br>   &lt;/script&gt;`;</pre><p>In order to “pass” rendered state to the app, we need to insert it before content is rendered within HTML.</p><pre>  const renderState = `<br>  &lt;script&gt;<br>    window.__INITIAL_STATE__ = ${serialize(state)}<br>  &lt;/script&gt;`;<br><br>  const html = `&lt;html&gt;<br>      &lt;head&gt;&lt;title&gt;Vue SSR&lt;/title&gt;<br>      &lt;link rel=&quot;stylesheet&quot; href=&quot;${manifest[&quot;app.css&quot;]}&quot; /&gt;<br>      &lt;/head&gt;<br>      &lt;body&gt;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>      &lt;/body&gt;<br>      &lt;/html&gt;`.replace(<br>  &#39;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;&#39;, `${renderState}&lt;div id=&quot;app&quot;&gt;${content}&lt;/div&gt;`</pre><p>Ok, let’s rebuild the application again and restart the server.</p><p>If we try to click in the app, we will find out that application is not responsive. Clicking the “Increment”/”Reset” buttons want change application state. This is because the app is completely static and we didn’t do a hydration step on the client.</p><p><em>What is hydration? Hydration is a process of creating on the client the same Vue application that was run on the server, matching each of the components DOM elements, and attaching DOM event listeners to them.</em></p><p>In order to hydrate the app, we need to include client-side code to our HTML server response.</p><p>Let’s put app.css and app.js to the HTML head and update server to serve the static content from ./dist/client folder.</p><pre>const clientManifest = require(path.join(<br>  __dirname,<br>  &quot;./dist/client/client-manifest.json&quot;<br>));<br><br>...<br><br>const distPath = &quot;./dist/client&quot;;<br>server.use(&quot;/img&quot;, express.static(path.join(__dirname, distPath, &quot;img&quot;)));<br>server.use(&quot;/js&quot;, express.static(path.join(__dirname, distPath, &quot;js&quot;)));<br>server.use(&quot;/css&quot;, express.static(path.join(__dirname, distPath, &quot;css&quot;)));<br>server.use(<br>  &quot;/favicon.ico&quot;,<br>  express.static(path.join(__dirname, distPath, &quot;favicon.ico&quot;))<br>);<br><br>...<br><br>// handle all urls in our application<br>server.get(&quot;*&quot;, async (req, res) =&gt; {<br>  const { content, state } = await renderApp(req.url);<br><br>  const renderState = `<br>    &lt;script&gt;<br>      window.__INITIAL_STATE__ = ${serialize(state)}<br>    &lt;/script&gt;`;<br>  <br>    const html = `&lt;html&gt;<br>        &lt;head&gt;&lt;title&gt;Vue SSR&lt;/title&gt;<br>        &lt;link rel=&quot;stylesheet&quot; href=&quot;${clientManifest[&quot;app.css&quot;]}&quot; /&gt;<br>        &lt;script defer=&quot;defer&quot; src=&quot;${clientManifest[&quot;chunk-vendors.js&quot;]}&quot;&gt;&lt;/script&gt;<br>        &lt;script defer=&quot;defer&quot; src=&quot;${clientManifest[&quot;app.js&quot;]}&quot;&gt;&lt;/script&gt;<br>        &lt;/head&gt;<br>        &lt;body&gt;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>        &lt;/body&gt;<br>        &lt;/html&gt;`.replace(<br>    &#39;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;&#39;, `${renderState}&lt;div id=&quot;app&quot;&gt;${content}&lt;/div&gt;`<br><br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);<br>  res.send(html);<br>});</pre><p>Now, when HTML is rendered and returned from the server, browser will download client side code, hydrate the app and we will get a fully interactive Vue web page.</p><p>The last thing we need to do is to set the initial store state in the client app. In order to do that, let’s open the main.js file and apply the initial state to the store.</p><pre>import { createApp } from &quot;./app&quot;;<br>import store from &quot;./store&quot;;<br><br>// initialize the store with server-initialized state.<br>// the state is determined during SSR and inlined in the page markup<br>if (window &amp;&amp; window.__INITIAL_STATE__) {<br>  store.state.value = window.__INITIAL_STATE__;<br>}<br><br>createApp().use(store).mount(&quot;#app&quot;, true);</pre><p>If we now build the app and restart the server, we will get a fully interactive Vue web page as result.</p><p>Thats it, we’ve went through steps on how to set up the state management for the SSR app. The final code is available on <a href="https://github.com/mladenbolic/vue-ssr/tree/vue-ssr-part-2">Github</a>.</p><p>In the next article we are going to show <a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-3-set-up-vue-router-with-ssr-a9e7fde9e089">how to Set up Vue Router with SSR</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5427d65d3cfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSR with Vue.js (Part 1)]]></title>
            <link>https://medium.com/@mladen.bolic/ssr-with-vue-js-part-1-1d860a27cdfb?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d860a27cdfb</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 12:35:01 GMT</pubDate>
            <atom:updated>2025-02-12T08:34:35.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*gJ-GjPR16zieZ-v7" /></figure><p>This is the first in the series of articles on how to se up SSR with Vue.js.</p><ul><li>SSR with Vue.js (Part 1)</li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-2-set-up-state-management-with-ssr-5427d65d3cfb">SSR with Vue.js (Part 2) — Setting Up State Management with SSR</a></li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-3-set-up-vue-router-with-ssr-a9e7fde9e089">SSR with Vue.js (Part 3) — Setting Up Vue Router with SSR</a></li><li><a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-4-setting-up-open-graph-meta-tags-with-ssr-dc4370b542c5">SSR with Vue.js (Part 4) — Setting Up Open Graph Meta Tags with SSR</a></li></ul><p>Server-side rendering (SSR) is a popular technique for rendering a client-side Single Page Application (SPA) on the server and then sending a fully rendered page as a response. SSR allows us to get faster response times, better SEO, but it also comes with drawbacks, including increased server side load, more robust application setup, and the need for an additional Node.js server to serve content.</p><p>In the following sections we are going to go through a basic setup for Vue.js SSR applications.</p><p>Note, if you are using <a href="https://nuxt.com/">Nuxt</a> or <a href="https://vite.dev/">Vite</a> you should already have a built in support for server-side rendering.</p><h3><strong>Creating Project</strong></h3><p>First, we’ll create a new Vue 3 project. Ensure that Vue CLI is installed on your machine before proceeding.</p><p>Open your terminal and type:</p><pre>$vue create vue-ssr</pre><p>In the project setup flow, let’s select manual configuration but stay with all preselected features. This will give us dedicated config files for features (Babel, ESlint) and make our code a bit cleaner.</p><h3>Server Setup</h3><p>Since we are setting up server-side rendering, we also need a server. We’ll use <a href="https://expressjs.com/">Express</a> for this purpose. Let’s install the server in the same directory as our Vue app.</p><pre>$npm i express</pre><p>Now we need to create a new file, let’s call it server.js, and we are going to populate it with some basic configuration.</p><p>Our server will handle all HTTP requests and respond with HTML content.</p><pre>const express = require(&quot;express&quot;);<br><br>const server = express();<br><br>// handle all urls in our application<br>server.get(&quot;*&quot;, async (req, res) =&gt; {<br>  const html = `&lt;html&gt;<br>      &lt;head&gt;&lt;title&gt;Vue SSR&lt;/title&gt;<br>      &lt;/head&gt;<br>      &lt;body&gt;Hello!!&lt;/body&gt;<br>      &lt;/html&gt;`;<br><br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);<br>  res.send(html);<br>});<br><br>server.listen(8083);<br><br>console.log(`Running on http://localhost:8083`);</pre><p>To check if everything is working ok, start the server and visit http://localhost:8083 in your browser. You should be able to see Hello!! message in your browser.</p><pre>$node server.js</pre><p>As a next step, we are going to create a new application build that is going to be rendered and served from Node.js server.</p><h3>SSR Build Configuration</h3><p>Let’s open vue.config.js and start working on setting up a custom Vue configuration.</p><p>We’ll use chainWebpack to change Vue’s default Webpack config. It will allow us to programmatically add named rules and plugins for our SSR build.</p><p>First, we’ll define an environment variable, SSR, to specify whether this is a server-side build. This will help differentiate between SSR and standard client-side builds.</p><pre>const { defineConfig } = require(&quot;@vue/cli-service&quot;);<br><br>module.exports = defineConfig({<br>  transpileDependencies: true,<br>  chainWebpack: (config) =&gt; {<br>    if (!process.env.SSR) {<br>      return;<br>    }<br>  },<br>});</pre><p>Let’s see how the application build should work.</p><ul><li>If SSR is <strong>not set</strong>, we will keep the default build configuration without any modifications.</li><li>If SSR <strong>is set</strong>, we will adjust the Webpack configuration to prepare the code for server-side rendering. Specifically, we will set the build target to node and set the target library to commonjs2. This will ensure that Node.js can use Vue&#39;s module exports and execute the code on the server.</li></ul><pre>const { defineConfig } = require(&quot;@vue/cli-service&quot;);<br><br>module.exports = defineConfig({<br>  transpileDependencies: true,<br>  chainWebpack: (config) =&gt; {<br>    if (!process.env.SSR) {<br>      return;<br>    }<br><br>    config.target(&quot;node&quot;);<br>    config.output.libraryTarget(&quot;commonjs2&quot;);<br>  },<br>});</pre><p>Next, we are going to set up our Webpack manifest file and configure the build modules.</p><h3>Setting Webpack Manifest and Build Modules</h3><p><em>What is a Webpack manifest file? A Webpack manifest file is a JSON file that maps source filenames to their corresponding build output files. It uses key/value pairs, allowing you to easily access specific files and their built versions.</em></p><p>We are going to use webpack-manifest-plugin library to generate our manifest file, so let’s install it.</p><pre>$npm i -D webpack-manifest-plugin</pre><p>Now when the library is installed, let’s introduce a manifest plugin to our build configuration.</p><p>We will specify a name for our plugin and define the location (file name) for the resulting manifest file.</p><pre>config<br>      .plugin(&quot;manifest&quot;)<br>      .use(new WebpackManifestPlugin({ fileName: &quot;ssr-manifest.json&quot; }));</pre><p>The second thing we need to do is to add node externals.</p><p><em>What are Node externals? Node externals allow us to exclude any node_modules that does not need to be run on server which will make our build to run faster.</em></p><p>Let’s install node externals and exclude all node_modules, expect files needed for rendering HTML on the server-side. We will define those files in the allowList.</p><pre>npm i -D webpack-node-externals</pre><pre>config.externals(<br>  nodeExternals({<br>    allowlist: [<br>      /\.(css|sass|scss|less)$/,<br>      /\.(vue)$/,<br>      /\.(html)$/,<br>    ],<br>  })<br>);</pre><p>Since our code is going to run on the server, lets further optimize our build and disable things like code splitting and compression. This should speed up our build.</p><p>We can also disable a few plugins used by Vue CLI like hot module replacements, preload, prefetch which are only useful if we are running our code in the browser.</p><pre>config.optimization.splitChunks(false).minimize(false);<br><br>config.plugins.delete(&quot;hmr&quot;);<br>config.plugins.delete(&quot;preload&quot;);<br>config.plugins.delete(&quot;prefetch&quot;);<br>config.plugins.delete(&quot;progress&quot;);<br>config.plugins.delete(&quot;friendly-errors&quot;);</pre><p>Now, let’s check if our configuration is working as expected. Open the console, set the SSR environment variable, and then run the build.</p><pre>$SSR=1 npm run build</pre><p>Files app.e85bf469.js and app.2cf79ad6.css should be generated in our /dist folder (note, you will get different hash values for each Webpack build).</p><p>If we run the build without setting the SSR variable, we’ll get the usual Vue.js build with all optimizations, minifications, and chunk creations applied to the files.</p><p>Now, if we open the /dist folder, and you should see the generated ssr-manifest.json file, which contains a list of all the files from our build. For example:</p><pre>{<br>  &quot;app.css&quot;: &quot;/css/app.2cf79ad6.css&quot;,<br>  &quot;app.js&quot;: &quot;/js/app.e85bf469.js&quot;,<br>  &quot;favicon.ico&quot;: &quot;/favicon.ico&quot;,<br>  &quot;index.html&quot;: &quot;/index.html&quot;,<br>  &quot;app.e85bf469.js.map&quot;: &quot;/js/app.e85bf469.js.map&quot;<br>}</pre><p>For our SSR setup, we are going to focus on the first two key-value pairs, app.css and app.js from the manifest file.</p><p>Ok, now that our SSR build is configured, let’s jump to the creation of Vue.js SSR app.</p><h3>Creating SSR application</h3><p>For creating SSR app, we will use createSSRApp from Vue library which will create the application instance in the SSR hydration mode.</p><p><em>What hydration basically is, it transforms server side rendered HTML code into a fully interactive web application on the client side. Basically it creates on the client the same Vue application that was run on the server.</em></p><p>In order to make things clean from the start, we’ll use two main files in our project:</p><ul><li>main.js (for the client-side)</li><li>main.server.js (for the server-side)</li></ul><p>Since we already have main.js, let’s create main.server.js inside the src folder:</p><pre>import App from &quot;./App.vue&quot;;<br>import { createSSRApp } from &quot;vue&quot;;<br><br>const app = createSSRApp(App);<br>export default app;</pre><p>Now, we need to change our Webpack configuration to use main.server.js for handling the SSR app. Let’s change vue.config.js and set up main application file for server-side rendering.</p><pre>config.entry(&quot;app&quot;).clear().add(&quot;./src/main.server.js&quot;);</pre><p>Now it’s time to set up Node.js server.</p><h3>Rendering Html on Server</h3><p>We will use renderToString to render HTML which will be sent as the HTML response from the server.</p><p>First, we will import app.js into the server code. But how do we know which file path to use for import since file hash suffix is changing on each build? Easy, we can access this value using our manifest file. So, let’s open server.js and do just that.</p><pre>const path = require(&quot;path&quot;);<br>const manifest = require(path.join(__dirname, &quot;./dist/ssr-manifest.json&quot;));<br><br>const appPath = path.join(__dirname, &quot;./dist&quot;, manifest[&quot;app.js&quot;]);<br>const app = require(appPath).default;</pre><p>Now, with the main app file accessible, we can get hydrated app from default export, get the app content using renderToString and send it back in the HTML response.</p><pre>const { renderToString } require(&quot;@vue/server-renderer&quot;);<br><br>...<br><br>// handle all urls in our application<br>server.get(&quot;*&quot;, async (req, res) =&gt; {<br>  const content = await renderToString(app);<br><br>  const html = `&lt;html&gt;<br>      &lt;head&gt;&lt;title&gt;Vue SSR&lt;/title&gt;<br>      &lt;link rel=&quot;stylesheet&quot; href=&quot;${manifest[&quot;app.css&quot;]}&quot; /&gt;<br>      &lt;/head&gt;<br>      &lt;body&gt;${content}&lt;/body&gt;<br>      &lt;/html&gt;`;<br><br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);<br>  res.send(html);<br>});</pre><p><em>Note, we are getting the url of </em><em>app.css file the same way we are accessing the location of </em><em>app.js file.</em></p><p>Now, if we restart our server and open <a href="http://localhost:8083,">http://localhost:8083</a> in the browser<a href="http://localhost:8083,">,</a> we will see the Home page as a response and that our server side application is rendering properly. But, something is not quite right, let’s see what…</p><p>If you open web console and check responses for <a href="http://localhost:8083/">http://localhost:8083/</a> and <a href="http://localhost:8083/app.css">http://localhost:8083/app.css</a>, you will see that they both return same HTML content in the response. That’s not good, HTML should be returned only for page requests, not for the static assets. Let’s fix this.</p><p>Open the server.js file and map static content requests to the corresponding locations in the /dist folder (e.g., /img URLs should map to ./dist/img).</p><pre>const server = express();<br><br>const distPath = &quot;./dist&quot;;<br>server.use(&quot;/img&quot;, express.static(path.join(__dirname, distPath, &quot;img&quot;)));<br>server.use(&quot;/js&quot;, express.static(path.join(__dirname, distPath, &quot;js&quot;)));<br>server.use(&quot;/css&quot;, express.static(path.join(__dirname, distPath, &quot;css&quot;)));<br>server.use(<br>  &quot;/favicon.ico&quot;,<br>  express.static(path.join(__dirname, distPath, &quot;favicon.ico&quot;))<br>);</pre><p>Now, whenever our server gets a static content request, we are going to serve it from a proper location instead of returning HTML content.</p><p>Let’s restart the server and visit <a href="http://localhost:8083/">http://localhost:8083/</a>. Now, page should be styled properly, and the web console should show that the correct content is served for each static asset request.</p><p>That concludes the first part of our SSR with Vue.js series. In the next article, we’ll cover <a href="https://medium.com/@mladen.bolic/ssr-with-vue-js-part-2-set-up-state-management-with-ssr-5427d65d3cfb">how to set up State management with SSR</a>.</p><p>The sample code is available on <a href="https://github.com/mladenbolic/vue-ssr/tree/vue-ssr-part-1">Github</a>. Stay tuned for more SSR-related articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d860a27cdfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySQL: Solving Duplicate Record Issue With Null Columns]]></title>
            <link>https://medium.com/@mladen.bolic/mysql-solving-duplicate-record-issue-with-null-columns-132d788b6997?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/132d788b6997</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[race-condition]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 20:58:35 GMT</pubDate>
            <atom:updated>2019-12-10T15:16:47.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem</h3><p>We want to make our MySQL records unique and avoid creating duplicate records in the table.</p><p>The table itself has unique set of columns and if at least one of them can have <em>null</em> values, MySQL will treat <em>null</em> column values as non-unique i.e. it will treat them as if they have different values. At the end, we will end up with duplicate records inside of our table.</p><p>So is there a way to solve duplicate record issue in MySQL when we have null column values?</p><h3>Solution</h3><p>Yes, there is. The idea is to apply unique constraint on our table columns, but before that, we just need to do some tweaks with our column values.</p><p>In short, we need somehow to “force” MySQL to treat all <em>null</em> column values as unique.</p><p>One way to achieve this is to create new metadata column (lets call it <em>hash)</em> which will be used to calculate the uniqueness of database records.</p><p>In order to do that we will take all columns that make our record unique, concatenate them and apply MD5 hash function on a resulting string and save it to our <em>hash</em> column.</p><p>In case when column value is <em>null</em>, we would first set it to default constant value e.g. 0 and then concatenate to other unique fields.</p><p>If two records have same <em>hash</em> column value they would be considered as duplicates.</p><p>Now, lets jump to SQL queries that we will use to setup this on database level.</p><p>First we will add soft delete flag to our document table.</p><pre>-- add &#39;deleted&#39; column for soft delete<br>ALTER TABLE document ADD deleted CHAR(36) DEFAULT NULL;</pre><p><em>Note: For soft delete we do not use boolean database value (true/false), instead we use generated UUID in order to allow multiple deletes of the same document type, hence we use CHAR(36) to store its value. If delete flag is not set, we will allow only one record to exist at the same time, forcing number of non-deleted records to only one at the time.</em></p><p>Now, lets create our <em>hash</em> column.</p><p>Since we are using MySQL 5.6, we cannot use <a href="https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html">MySQL generated column</a> feature introduced in MySQL 5.7, instead we need to ask good old triggers for help here.</p><p>We will create 2 triggers: insert trigger and update trigger, and they will be used to recalculate <em>hash</em> column value each time we change document data.</p><pre>-- add &#39;hash&#39; column for checking document uniqueness<br>ALTER TABLE document ADD hash CHAR(32) DEFAULT NULL;</pre><pre>-- create insert trigger for setting the &#39;hash&#39; column value<br>CREATE TRIGGER document_insert<br>  BEFORE INSERT<br>  ON document<br>  FOR EACH ROW<br>  SET NEW.hash = (MD5<br>    (CONCAT_WS(<br>          ifnull(NEW.deleted, 0),<br>          NEW.title,<br>          NEW.userid,<br>          ifnull(NEW.typeid, 0)<br>        )<br>    ));</pre><pre>-- create update trigger for setting the &#39;hash&#39; column value<br>CREATE TRIGGER document_update<br>  BEFORE UPDATE<br>  ON document<br>  FOR EACH ROW<br>  SET NEW.hash = (MD5<br>    (CONCAT_WS(<br>          ifnull(NEW.deleted, 0),<br>          NEW.title,<br>          NEW.userid,<br>          ifnull(NEW.typeid, 0)<br>        )<br>    ));</pre><p><em>Note: typeid is nullable column and thats why we cannot apply simple SQL unique constraint to tables columns (MySQL will treat all null columns as if the columns have different values).</em></p><p>Now that we created the <em>hash</em> column and its triggers, lets clean the database and remove all duplicate documents.</p><p>If two or more documents have same <em>hash</em> value we will consider them as duplicates. We will leave document with the lowest id (first record that was inserted) and delete the rest of them.</p><pre>-- delete duplicate documents (having same &#39;hash&#39; value)<br>UPDATE document<br>SET<br>    deleted = UUID()<br>WHERE hash IN (<br>  -- get all duplicate &#39;hash&#39; values (more than 1 record for given hash) i.e. get all duplicate documents<br>  SELECT result.hash FROM (<br>                            SELECT d.hash, <em>count</em>(*) as total<br>                            FROM document d<br>                            GROUP BY d.hash<br>                            HAVING total &gt; 1<br>                          ) AS result<br>)<br>  -- from duplicate documents, keep document with lowest id (oldest document)<br>  AND id NOT IN (<br>  SELECT result.id FROM (<br>                          SELECT <em>min</em>(d.id) as id, <em>count</em>(*) as total<br>                          FROM document d<br>                          GROUP BY d.hash<br>                          HAVING total &gt; 1<br>                        ) AS result<br>);</pre><p>After all duplicate documents are deleted we can apply the unique constraint on our <em>hash</em> column.</p><pre>-- make &#39;hash&#39; value unique<br>ALTER TABLE document ADD UNIQUE `unique_hash_idx`(hash);<br>ALTER TABLE document MODIFY hash CHAR(32) NOT NULL DEFAULT &#39;NA&#39;;</pre><p>Now, whenever we try to insert a duplicate document, we will get an error on database level, no additional records will be created and our database will be in consistent state.</p><p>Good thing with this solution is that we do not need to change anything on our application level.</p><p>Bad thing is that if we introduce new field for documents that should be included to the list of unique fields, we need to change the hash calculation on database level. But that’s the thing we kind of agreed to when we decided to handle unique records on database level.</p><h3>Conclusion</h3><p>We experienced this duplicate record issue when one of our Microservices (two running instances) received two external events of the same type at the same time. This caused event race condition where each of the server instance was handling the event and creating new document record. First instance was not aware that the second instance was handling the same event. In our case we managed to solve the creation of duplicate records by forcing record uniqueness on database level applying the described solution.</p><p>Hope this article gave you some ideas how to solve similar issues on your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=132d788b6997" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting OpenFeign Hystrix Timeout]]></title>
            <link>https://medium.com/@mladen.bolic/setting-openfeign-hystrix-timeout-5f2da65d3c96?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f2da65d3c96</guid>
            <category><![CDATA[hystrix]]></category>
            <category><![CDATA[openfeign]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dropwizard]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Sat, 22 Jun 2019 13:01:51 GMT</pubDate>
            <atom:updated>2019-06-22T13:01:51.668Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Libraries implementing </em><a href="https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern"><em>Circuit Breaker Pattern</em></a><em> help us build latency and fault-tolerant distributed systems which is very important in the era of micro-service architecture.</em></p><h3>Introduction</h3><p>In our car rental business we received a business requirement to connect with our partners and offer their cars if we do not have cars available for rental. Our partners gave us an API endpoint and our job was to check if car of given type is available on their parking lot, if yes, we were offering their car to customers. Simple as that.</p><p>We wanted to make our system fault tolerant so we decided to use a library that implements Circuit Breaker Pattern.</p><p>We worked previously with several Circuit Breaker implementations: Spring Hystrix, Javaslang (now <a href="https://github.com/vavr-io/vavr">Vavr</a>, amazing library, highly recommend to give it a try on your projects), but this time we decided to give it a try with OpenFeign, a library that is using Hystrix internally.</p><h3><strong>Implementation</strong></h3><p>The client implementation was fairly simple. We introduced new interface containing our partners Garage service endpoints. Our Rental service job was to send requests to Garage service, check if there were any cars for rental, if yes, we would offer them to our clients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f826ebd2d37bf43cd11f2b44fc2b21ae/href">https://medium.com/media/f826ebd2d37bf43cd11f2b44fc2b21ae/href</a></iframe><p>Implementation was pretty straightforward. We’ve tested it, deployed the code to production. Everything worked like a swiss watch.</p><h3>Problem</h3><p>After few weeks a holiday season came and then we noticed that all our Hystrix requests started to timeout. Garage service became too busy and it was struggling to handle all requests. Not only ours but also from other affiliates. So, we needed to find a quick (not perfect) solution on our side.</p><p>After quick investigation we discovered that Hystrix has a default timeout set to 500ms and apparently that wasn’t enough for Garage service during holiday peaks.</p><h3>Solution</h3><p>The solution for this issue was fairly simple: setup the higher timeout for Hystrix requests, 2000ms seemed quite reasonable. So how do we configure the timeout value for OpenFeign?</p><p>We used Dropwizard for our service implementation. For those of you coming from Spring Boot world a Dropwizard project structure should look quite familiar.</p><p>We have a main application class RentalServiceApplication responsible for bootstraping the application. For configuration we use config.yaml file that contains parameters like database connection url, caching settings and in our case garage service url and Hystrix properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d9f35c842f0012e8568ee8c0512e0ee/href">https://medium.com/media/1d9f35c842f0012e8568ee8c0512e0ee/href</a></iframe><p>In order to read the Hystrix configuration we needed to “map” the config params to our configuration class RentalServiceConfiguration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/269179239e9db4eecd16306ce6a54fb3/href">https://medium.com/media/269179239e9db4eecd16306ce6a54fb3/href</a></iframe><p><em>Getter and </em><em>Setter annotations are part of another great library </em><a href="https://projectlombok.org/"><em>Lombok</em></a><em> and they are here to help us reduce the code noise.</em></p><p>Now, we needed to apply this configuration to Hystrix.</p><p>For configuration settings, Hystrix is using <strong>archaius-core</strong> library which has a runtime dependency on <strong>commons-configuration</strong>. In order to change the Hystrix timeout, we needed to make this library available for us at compile time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36386ccb9643a417ee01bb5c1751d687/href">https://medium.com/media/36386ccb9643a417ee01bb5c1751d687/href</a></iframe><p>Now that we had commons-configuration, we could access ConfigurationManager and configure the Hystrix, using Hystrix properties from our configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ee5c7247bf56cd8b7e21f620837fe1e/href">https://medium.com/media/0ee5c7247bf56cd8b7e21f620837fe1e/href</a></iframe><p>And that’s it. Timeouts were fixed and we were back on track.</p><h3>Conclusion</h3><p>We showed you how to setup the Hystrix timeout for OpenFeign client in your projects. <br>Great thing about this solution is that you can specify any official <a href="https://github.com/Netflix/Hystrix/wiki/Configuration">Hystrix configuration property</a> in your config file and it will be immediately applied to Hystrix. E.g. if you choose to change the error threshold for circuit breaker, you just need to introduce hystrix.command.default.circuitBreaker.errorThresholdPercentage in your config.yaml and the configuration will be applied to Hystrix client.</p><p>That’s all on the topic how to setup the Hystrix timeout for OpenFeign client. Hope you’ve enjoyed it and will found it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f2da65d3c96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Akka Crawler]]></title>
            <link>https://medium.com/@mladen.bolic/implementing-akka-crawler-864d4f66461?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/864d4f66461</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[akka]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Thu, 22 Nov 2018 11:22:07 GMT</pubDate>
            <atom:updated>2018-11-22T11:22:07.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOitzETp8XhNIsVchxfBoQ.png" /></figure><h3>Introduction</h3><p>Building thread safe, highly concurrent applications in Java can be hard. As a developer you need to take care about thread synchronization, deadlocks, race conditions and due to introduced thread boilerplate, this kind of applications can be hard to read and maintain. Luckily, Akka can help us here to manage application concurrency, thereby reducing the overall complexity of the code.</p><p>So what is Akka?</p><h4>Akka</h4><p><a href="https://akka.io/">Akka</a> is a set of libraries for building highly scalable, resilient and responsive applications using Actor Model. Actor is the main building block of an Akka application. By using actors, developers are freed from responsibility of dealing explicitly with threads and thread management.</p><p>Actors are very lightweight and there can be several million actor instances running within a single application.</p><p>Actors communicate with each other by exchanging asynchronous messages. We can think of actor’s messages as commands and events that are interchanged between actors. In a way messages are revealing actor’s public API, thus it is important to use descriptive names and rich semantics to describe their role inside actor-based system. Since messages are shared between different threads, they should be immutable.</p><p>So how do we start building one Akka application?</p><p>We start by creating one or more Actors using ActorSystem. All other actors should be created by the same ActorSystem or by one of its children actors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa466750183107530e98ba94cca72357/href">https://medium.com/media/fa466750183107530e98ba94cca72357/href</a></iframe><p>Additionally, every actor has a createReceive method for defining type of messages it is going to handle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c636d527fa57eee9b217b4a7b1b3f9d2/href">https://medium.com/media/c636d527fa57eee9b217b4a7b1b3f9d2/href</a></iframe><p>As for common programming practices, it’s usual to keep the Actor and its messages as close as possible i.e. messages are defined as static inner classes inside an actor. This makes it easier to understand how actor is handling its messages and its business logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a74b62cad77d1a40a265a0c5c2033620/href">https://medium.com/media/a74b62cad77d1a40a265a0c5c2033620/href</a></iframe><p>Akka enforces parental supervision, hence every actor is going to be supervised by its parent. What this means is that if an error occurs in a child actor, his parent is going to decide how to handle this error. It could resume, stop, restart a child actor or escalate an error up the hierarchy. <br>This is one of the main features of Akka which allow us to build fault tolerant applications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3471a6676e5c36fef21d86e055c73b/href">https://medium.com/media/5c3471a6676e5c36fef21d86e055c73b/href</a></iframe><p>Ok, now that we know what Akka is, let’s start implementing our crawler.</p><h3>Implementation</h3><p>Our goal will be to create a website crawler that is going to traverse a website and download all his files to local file system.</p><p>Let’s start by describing the overall architecture of our application.</p><p>Our Akka crawler we will be using 3 types of actors: SupervisorActor, FileDownloadActor and LinkExtractActor.</p><p><em>SupervisorActor </em>is going to supervise other two actors and is going to hold current crawl status. <em>FileDownloadActor</em> is going to be responsible for downloading a file and saving it to the local file system. The <em>LinkExtractActor </em>is going to read the content of a downloaded file, extract the links from it and send back list of urls to the <em>SupervisorActor</em>. <em>SupervisorActor</em> is going receive the list of urls, add them to the list of remaining urls and distribute new urls to <em>FileDownloadActor</em>. Crawling stops when all urls are processed and all website files are downloaded to local file system.</p><h4>Supervisor Actor</h4><p>As stated before <em>SupervisorActor</em> is going to be responsible for orchestrating <em>FileDownloadActor</em> and <em>LinkExtractActor</em> and delegating work to them.</p><p>We trigger the website crawling, by sending StartCrawling message to our <em>SupervisorActor</em>. StartCrawling message will contain the http link of the website we are going to crawl and whose content we are going to download.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e8101410f8e06d28721b82b6c86141a/href">https://medium.com/media/6e8101410f8e06d28721b82b6c86141a/href</a></iframe><p>Upon receiving the message, <em>SupervisorActor</em> will save the url to the list of remaining urls and pass the url to <em>FileDownloadActor</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b90b13a60888fbf8e3959957a718886/href">https://medium.com/media/8b90b13a60888fbf8e3959957a718886/href</a></iframe><h4>File Download Actor</h4><p><em>FileDownloadActor</em> is going to receive DownloadFile message sent from <em>SupervisorActor</em>, read the url part from it and download a file from specified url. Once it’s done with downloading, it will notify the <em>SupervisorActor</em> that file is downloaded and will send back the location where the file is saved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b54b31a80da225296729353a03d63fcc/href">https://medium.com/media/b54b31a80da225296729353a03d63fcc/href</a></iframe><p>There are two strategies we can use to handle errors during execution of an Akka actor. Propagate the thrown error to the parent actor and let the parent actor handle it depending on its supervisor strategy, or we can send an error message to the parent actor.</p><p>For file download we will use the latter solution and send FileDownloadError if something goes wrong. <br>Using error message will allow us to send additional data to parent actor. In our case we will send url within the message and that will give us the ability to keep track of all file urls that couldn’t be handled by <em>FileDownloadActor</em>.</p><h4>Link Extract Actor</h4><p>Once file is downloaded, <em>SupervisorActor</em> will get the FileDownloadResult message, read the file path from it and call the <em>LinkExtractActor</em> passing him the path information within ExtractLinks message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99bb33675a971a6a0bdab003e92748a7/href">https://medium.com/media/99bb33675a971a6a0bdab003e92748a7/href</a></iframe><p><em>LinkExtractActor</em> will receive the message, read the file content, extract all links (JavaScript, CSS, images) and send back the result to the <em>SupervisorActor</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/610c1c06c424d51e32031cba9a738f2b/href">https://medium.com/media/610c1c06c424d51e32031cba9a738f2b/href</a></iframe><p><em>SupervisorActor</em> will add new urls to the list of remaining urls and pass them to <em>FileDownloadActor</em> for further processing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ad498609ca9e5b3e40af5e991ea2487/href">https://medium.com/media/3ad498609ca9e5b3e40af5e991ea2487/href</a></iframe><p>If an error occurs during link extraction, we are going to notify the parent actor about it, but this time we are going to let the child actor to fail (i.e. throw LinkExtractException) instead of sending error message. This way we are letting the parent actor to handle the error depending on its SupervisorStrategy. In our case, <em>SupervisorActor</em> will match the exception and restart the actor, therefore clearing its internal state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bae6f65cc15e91bf07843e8b2b629fb/href">https://medium.com/media/6bae6f65cc15e91bf07843e8b2b629fb/href</a></iframe><p>Once we process all urls, we can print the final crawling result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40299d30900a6d517d31ada65d741daa/href">https://medium.com/media/40299d30900a6d517d31ada65d741daa/href</a></iframe><p>Now, if we run the application, everything should work as expected. <br><em>SupervisorActor</em> will receive <em>StartCrawling</em> message and start delegating the work to <em>FileDownloadActor</em> and <em>LinkExtractActor</em>. <em>FileDownloadActor</em> and <em>LinkExtractActor</em> are going to do their job, they are going to be download files, extract links…But, can we do more? Can we speed the things up?</p><p>The answer is “Yes”. Let us see how to do this.</p><h4>Routing</h4><p>If you remember, we are using ActorSystem to initialize SupervisorActor. At the same time we are defining how should we create FileDownloadActor. Same is true for LinkExtractActor but we will omit its code here to make our example more readable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e8101410f8e06d28721b82b6c86141a/href">https://medium.com/media/6e8101410f8e06d28721b82b6c86141a/href</a></iframe><p>If you take a look at getFileDownloadActorCreator method, you will see that we are creating one actor instance for handling file downloads. This is not very efficient. In order to speed things up we will introduce <em>Round Robin Router</em>.</p><p>By using the <em>Round Robin Router</em>, actor system is able to distribute messages to multiple actor instances allowing them to work in parallel in order to get the job done.</p><p>In our case, <em>SupervisorActor</em> will distribute <em>DownloadFile</em> messages to multiple instances of <em>FileDownloadActor</em>. The rest of the implementation will stay the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbe113ed4078c5582aaf286a6ec8f5e7/href">https://medium.com/media/bbe113ed4078c5582aaf286a6ec8f5e7/href</a></iframe><p>So, what we basically did is, we boosted our application by introducing several actor instances to handle our job instead of using only one and all that by changing one line of code. Pretty cool, right?</p><h3>Conclusion</h3><p>As we saw from previous example, Akka Actor Model is a very powerful tool for building reactive, high performance, concurrent applications. It releases developers from responsibility to explicitly handle the threading issues and allows them to concentrate on writing business logic.</p><p>By introducing routing we are getting additional benefit of speeding up the application, allowing actor system to distribute the work among several actors instances instead of using one actor to handle the same job.</p><p>The full source code of the example is available on <a href="https://github.com/mladenbolic/akka-website-crawler">Github</a>. For more info on how to run the example, please see the <a href="https://github.com/mladenbolic/akka-website-crawler/blob/master/README.md">README</a> file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=864d4f66461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Static Code Analysis for Java]]></title>
            <link>https://medium.com/@mladen.bolic/setting-up-static-code-analysis-for-java-3428dc79f7f9?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/3428dc79f7f9</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Thu, 20 Sep 2018 09:51:24 GMT</pubDate>
            <atom:updated>2019-12-01T08:24:14.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*QCO711UYo8-a4mDqKiTfAA.jpeg" /></figure><h3>Introduction</h3><p>In this article we will go through a basic setup of static code analysis for a Java project.</p><p>Why static code analysis is important? It helps us to ensure the overall code quality, to fix bugs in early stage of development and to ensure that each developer is using the same coding standards when writing the code.</p><p>There are 3 basic tools we are going to use for our static code analysis: <a href="http://checkstyle.sourceforge.net/">CheckStyle</a>, <a href="http://findbugs.sourceforge.net/">Findbugs</a>, <a href="https://pmd.github.io/">PMD</a>.</p><h4>CheckStyle</h4><p>CheckStyle is a tool that helps programers to write a code that aligns with already agreed coding standards. It automatically checks if code adheres to the coding standards used on a project.</p><h4>FindBugs</h4><p>Fine people of University of Maryland build this fantastic tool for us. What it basically does for us is, of course, finding bugs in our code :)). FindBugs analyses our code and generates a report giving us a list of all the bugs that could cause a program to misbehave. One of the good examples of the bugs that could be detected are: infinite loops, unused variables, security, threading issues and many more.</p><h4>PMD</h4><p>PMD is another useful tool in our static code analyzers toolbox. Beside reporting many coding issues (e.g. possible memory leaks), PMD can check if our code was commented properly, if our variables are named properly, if our method contains more than specified number of lines. PMD is highly configurable and the latest releases play quite well with <a href="https://projectlombok.org/">Lombok</a> annotations (previously we needed to define custom excluded rules in order for PMD to play nice with Lombok).</p><p><a href="https://pmd.github.io/pmd-5.6.1/usage/cpd-usage.html">Copy/Paste Detector (CPD)</a> is integrated part of PMD and it is used to detect duplicated code in a source code.</p><h3>Setting Up Static Code Analysis</h3><p>We are going to use <a href="https://gradle.org/">Gradle</a> as our build tool. Gradle already has a set of plugins that we are going to use for our static code analysis.</p><p>Static analysis setup files will reside in ./gradle/static-code-analysis folder. Each of our static analysis tools will have it’s own dedicated folder, where we will hold additional configuration files for each of the tools. Finally, we’ll use staticCodeAnalysis.gradle to aggregate all our static code analysis settings. It will contain all the configuration settings needed to run static code analysis for our project.</p><p>Ok, let’s jump into setting the static code analysis.</p><p>Before starting configuring the plugins, we need to add the plugins to our Gradle script. Since we cannot run Copy/Paste detection using PMD plugin, we will use the <a href="https://github.com/aaschmid/gradle-cpd-plugin">Gradle CPD plugin</a> to do the job for us. In order to use Gradle CPD plugin, we need to specify the buildscript section before applying the plugin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/385dc2bacc6881ba0fbb86f0edec94a8/href">https://medium.com/media/385dc2bacc6881ba0fbb86f0edec94a8/href</a></iframe><p>Once the plugins are included in the build script, we can start configuring each of the plugins. First, we are going to configure the CheckStyle plugin.</p><h4>Setting CheckStyle</h4><p>For CheckStyle, we are going to set the ignoreFailures flag, toolVersion and configFile which will point to the location of a configuration file. As a base for our <a href="https://github.com/mladenbolic/static-code-analysis/blob/master/gradle/static-code-analysis/checkstyle/checkstyle.xml">configuration file</a>, we are going to use <a href="http://checkstyle.sourceforge.net/reports/google-java-style-20170228.html">Google Code Style</a> settings. The configurations are basically the same, the only difference is that we are going to use 4 space instead of 2 space indentation. And that’s it. Nothing more needs to be done for CheckStyle. Let’s setup the FindBugs next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d056a1707ab5936812a7d64605cd9a/href">https://medium.com/media/48d056a1707ab5936812a7d64605cd9a/href</a></iframe><p><em>We are explicitly setting the plugin not to ignore failures i.e. </em><em>ignoreFailures flag is set to </em><em>false. What that basically means is that our project build will fail if we run into any issue during our static code analysis check. If you think about it, this has a lot of sense. Our CI/CD pipeline should fail in case we run upon any issue in our code base. Being it compile failure, unit test failure, code analysis, as long as we have an issue, we shouldn’t be able to continue with our pipeline.</em></p><h4>Setting FindBugs</h4><p>In most cases we should specify only toolVersion and ignoreFailures. There are other options we could set here, such as specifying which bug detectors are going to be run or to include/exclude list of files that are going to be checked in our code base. For our example, we will leave the default values here: all default bug detectors will be run and we are not going to exclude any file from FindBugs detection. Let’s set the PMD next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0e6de51358e3caab64de4512473d98a/href">https://medium.com/media/e0e6de51358e3caab64de4512473d98a/href</a></iframe><h4>Setting PMD</h4><p>For PMD besides toolVersion and ignoreFailures, we are going to set the rule sets for our code analysis. We have can set the rule sets in two ways. We can specify them directly inside the PMD plugin configuration using ruleSets array, or we could extract the rule sets to separate xml file and reference the file using the ruleSetFiles configuration parameter. We are going to choose the latter option, since it is more descriptive and it allows us to provide exclusions to default rule sets categories (e.g. for codestyle category, we are excluding DefaultPackage, OnlyOneReturn rules, you can check out <a href="https://github.com/mladenbolic/static-code-analysis/blob/master/gradle/static-code-analysis/pmd/ruleset.xml">ruleset.xml</a> for full setup).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a97d1bdf72184f45c0a8e875efac6ac/href">https://medium.com/media/8a97d1bdf72184f45c0a8e875efac6ac/href</a></iframe><h4>Setting CPD</h4><p>For Copy/Paste bug detection we need to configure the CPD plugin. First, let’s set the minimumTokenCount to 100. This means that the plugin will detect duplicate code bug if it finds around 5–10 lines of the same code in separate places. If only 4 lines of code are matched, bug won’t be detected. One useful option (especially if you are using frameworks) is to set the ignoreAnnotations to true. It will allow us to ignore “false positives” and ignore cases where classes or methods have the same 5–6 lines of annotations. Finally, we’ll enable generating xml by setting xml.enabled to true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/291281ea0fd54243773be9161db1d3cd/href">https://medium.com/media/291281ea0fd54243773be9161db1d3cd/href</a></iframe><p>For remaining static analysis report plugins, we will enable generation of the html report instead of xml one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db84437201a41b0daeb9c91f374cd795/href">https://medium.com/media/db84437201a41b0daeb9c91f374cd795/href</a></iframe><p>Great!! We are done with the static analysis code configuration. Now we just need to include staticCodeAnalysis.gradle into our Gradle build script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f41f9f5cd454ad41ee3b7c7ed2d633/href">https://medium.com/media/83f41f9f5cd454ad41ee3b7c7ed2d633/href</a></iframe><h3>Running Static Code Analysis</h3><p>Static code analysis plugins will run with the same Java version used to run Gradle.</p><p>Each plugin will add its own dependencies to the Java plugin check task (e.g. pmdMain, cpdMain…). Whenever we run ./gradlew clean build, internally check task will be triggered and static analysis steps will be run for our project. If any of the code analysis steps fail, our build will fail as well. <br>Static code analysis reports will be generated under ./build/reports.</p><p>If in some situations we need to “loose” the specified static code rules we can always suppress static analysis errors by using @SuppressWarnings annotation. E.g. in order to suppress warning for having too many methods in a class, we could put @SuppressWargning(&quot;PMD.TooManyMethods&quot;) on given class.</p><p>We advise to keep static analysis “on” for the test classes as well. We should always treat tests as integrated part of our project. Test code should confirm to the same styles/rules we use throughout our project.</p><h3>Summary</h3><p>We went through a short explanation on how to setup the static code analysis for a Java project. Hope you got a good overview on how you can use it in your project, how it can help you to improve overall code quality and to detect bugs in early stage of project development.</p><p>The sample code is available on <a href="https://github.com/mladenbolic/static-code-analysis">Github</a>. Enjoy static code analyzing!</p><p>For anyone who want to use <a href="https://spotbugs.github.io/">SpotBugs</a> instead of <a href="http://findbugs.sourceforge.net/">FindBugs</a> (not maintained anymore) I’ve created a separate <a href="https://github.com/mladenbolic/static-code-analysis/tree/spotbugs">Github branch</a> with SpotBugs specific settings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3428dc79f7f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda Scheduler]]></title>
            <link>https://medium.com/@mladen.bolic/aws-lambda-scheduler-123c1d1ec0?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/123c1d1ec0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Tue, 21 Aug 2018 07:15:44 GMT</pubDate>
            <atom:updated>2018-08-21T07:15:44.617Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Forget about Quartz Scheduler, Spring Scheduler…let’s schedule with Lambda.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*5aLL6unVWZvPJwJm3FfpcQ.png" /></figure><p><em>The idea behind AWS Lambda Scheduler is very simple:</em></p><ul><li><em>AWS CloudWatch scheduled event will trigger AWS Lambda function</em></li><li><em>Lambda function will publish a message to SNS topic</em></li><li><em>Message will be pushed to SQS queue</em></li><li><em>Consumer service will receive message from the queue and execute an action</em></li></ul><p>In order to setup AWS Lambda Scheduler, we will go through following steps:</p><ol><li>Creating SNS topic</li><li>Setting up Lambda roles</li><li>Creating Lambda function</li><li>Setting CloudWatch trigger</li><li>Creating NodeJS service</li></ol><p>But before going through the steps, you need to <a href="https://aws.amazon.com/cli/">install</a> AWS Command Line Interface and <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html">configure</a> it using <em>AWS Access Key ID</em> and <em>AWS Secret Access Key</em> from your AWS account.</p><p>If you are all setup, let’s start creating our lambda scheduler.</p><h3>1. Creating SNS Topic</h3><p>First, we will create an SNS topic on which our lambda scheduler will publish messages.</p><p>Open a command line and execute the command for creating a topic:</p><pre>aws sns create-topic \<br>    --name scheduler-topic</pre><p>Save the topic TopicArn from command response, we are going to use it in subsequent steps (4. Setting CloudWatch Trigger, 5. Creating NodeJS Service).</p><h3>2. Setting Up Lambda Roles</h3><p>Before creating Lambda function, we need to setup two IAM roles for AWS Lambda:</p><ul><li>The execution role, that will allow AWS Lambda to execute the function on our behalf.</li><li>SNS publishing role, that will allow our lambda function to publish messages to SNS topic.</li></ul><h4>2.1 Creating Lambda Execution Role</h4><p>Let’s setup the policies that will allow AWS Lambda to execute the lambda function.</p><pre>aws iam create-role \<br>    --role-name &quot;lambda-scheduler-role&quot; \<br>    --assume-role-policy-document file://lambda-role-policy.json</pre><p>We are going to use standard lambda policy role setup:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/132b1e88302e26f621b8e9920e27c491/href">https://medium.com/media/132b1e88302e26f621b8e9920e27c491/href</a></iframe><p>Save Role.Arn role from command response, we are going to use it later in our setup (3. Creating Lambda Function).</p><h4>2.2 Creating Lambda SNS Publishing Role</h4><p>Now, let’s setup the policies that will allow AWS Lambda to publish messages to the SNS topic.</p><pre>aws iam put-role-policy \<br>    --role-name lambda-scheduler-role \<br>    --policy-name lambda-scheduler-publish-policy \<br>    --policy-document file://lambda-sns-policy.json</pre><p>In lambda-sns-policy.json under Resource we should specify the name of the topic we created in step 1, scheduler-topic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47e9118df22ab6dac1bf0a8ed7883a30/href">https://medium.com/media/47e9118df22ab6dac1bf0a8ed7883a30/href</a></iframe><p>Now that our Lambda IAM roles are setup, it’s time to create our Lambda function.</p><h3>3. Creating Lambda Function</h3><p>We will use NodeJS (JavaScript) to create our lambda function. First, let’s take a quick look at our function code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f9ba4dd15d6c0a3bacd70a3bcf969ff/href">https://medium.com/media/0f9ba4dd15d6c0a3bacd70a3bcf969ff/href</a></iframe><p>As you can see from the code, our Lambda function is quite simple. It will receive an CloudWatch event with topic name where it should publish a message, event.sns_topic. Then, it is going to call a method for publishing messages. And that’s it, it’s as simple as that.</p><p><em>We choose for our Lambda function to be topic agnostic (passing the topic ARN, instead of hardcoding it inside the function code). This way we are making it possible for a Lambda function to act as a central dispatcher for sending scheduled messages to different topics. E.g. we can have a 5min topic, 7am topic, and for each of them one or more subscribers that are going to be triggered at specific topic time interval (every 5min, every day at 7am etc.).</em></p><p>Now when we have our function code, we can create lambda function. But before we execute the command for creating AWS Lambda function, we need to prepare a deployment package.</p><p>A deployment package is a simple zip file containing lambda function code with all required libraries needed to run that code (in our case, since we use only aws-sdk, we need to zip only index.js file, no need for zipping extra libraries from node_modules).</p><p>So, let’s create our deployment package:</p><pre>zip lambda-scheduler.zip index.js</pre><p>Now when we have a deployment package, we can execute the command for creating AWS Lambda function:</p><pre>aws lambda create-function \<br>    --function-name &quot;lambda-scheduler-function&quot; \<br>    --runtime nodejs6.10 \<br>    --role arn:aws:iam::254308114278:role/lambda-scheduler-role \<br>    --handler index.handler \<br>    --description &quot;Lambda function for publishing messages to sns topics&quot; \<br>    --zip-file fileb://lambda-scheduler.zip</pre><p>And here is a short explanation for each of the parameters we are passing with our create command:</p><ul><li>role: is execution role ARN we got in step 2.1</li><li>handler: is the name of exported NodeJS function that AWS Lambda will invoke (name of the file index.js, exported function is handler, hence index.handler)</li><li>zip-file: is the path to our Lambda function deployment package</li></ul><p>Ok, our lambda function is all setup. Now let’s configure the CloudWatch event trigger that will invoke our lambda function.</p><h3>4. Setting CloudWatch Trigger</h3><p>CloudWatch trigger is very important in our setup, since it will be responsible for making actual calls that will trigger our lambda function on specified intervals. With each call we will send a topic name that will be triggered at given interval.</p><p>First, let’s create a self-triggered CloudWatch event rule that will trigger every 5 minutes (for our demo we choose 5 minute trigger rate, but you can choose any other value grater than 1 min):</p><pre>aws events put-rule \<br>    --name &quot;scheduler-topic-lambda-scheduler-trigger-rule&quot; \<br>    --schedule-expression &#39;rate(5 minutes)&#39;</pre><p>Next, let’s use the RuleArn from the result of previous command and add a permission for invoking Lambda function by CloudWatch:</p><pre>aws lambda add-permission \<br>    --function-name &quot;lambda-scheduler-function&quot; \<br>    --statement-id &quot;scheduler-topic-access-permission-id&quot; \<br>    --action &#39;lambda:InvokeFunction&#39; \<br>    --principal events.amazonaws.com \<br>    --source-arn &quot;arn:aws:events:us-east-1:254308114278:rule/scheduler-topic-lambda-scheduler-trigger-rule&quot;</pre><p>After specifying CloudWatch permissions, we need to specify an event rule and targets. For the event rule, we are going to use 5min event rule we already created, and as a target, we are going to use the lambda scheduler function and the SNS topic (from step 1) as its input data:</p><pre>aws events put-targets \<br>    --rule &quot;scheduler-topic-lambda-scheduler-trigger-rule&quot; \<br>    --targets &#39;{&quot;Id&quot; : &quot;1&quot;, &quot;Arn&quot;: &quot;arn:aws:lambda:us-east-1:254308114278:function:lambda-scheduler-function&quot;, &quot;Input&quot;: &quot;{\&quot;sns_topic\&quot;: \&quot;arn:aws:sns:us-east-1:254308114278:scheduler-topic\&quot;}&quot;}&#39;</pre><p><em>If you remember our lambda function code (from step 3.), it is going to read </em><em>sns_topic from CloudWatch event and publish a message to it.</em></p><p>Ok, our Lambda scheduler is all setup. In order to see it in action, let’s quickly setup a NodeJS service that is going to be triggered by this scheduler.</p><h3>5. Creating NodeJS Service</h3><p>Our NodeJS Service will be a simple subscriber. When lambda function sends a message to the queue, service will receive the message and it will “trigger” one of his actions (in our case, printing a message to the screen).</p><p>We want our service to receive messages from Lambda function, so we need to setup SQS queue for it.</p><p>Let’s start by creating the SQS queue (we won’t get into details how to setup the queue attributes. For more info please check <a href="https://docs.aws.amazon.com/cli/latest/reference/sqs/set-queue-attributes.html">the official AWS CLI reference page</a>):</p><pre>aws sqs create-queue \<br>  --queue-name service-queue\<br>  --attributes file://sqs-attributes.json</pre><p>Copy the QueueUrl from command response, and use it to updatequeueUrl in <a href="https://github.com/mladenbolic/aws-lambda-scheduler/blob/master/service/index.js">service code</a>.</p><p>Next, let’s retrieve queue ARN:</p><pre>aws sqs get-queue-attributes \<br> — queue-url &quot;https://queue.amazonaws.com/254308114278/service-queue&quot;<br> — attribute-names &quot;QueueArn&quot;</pre><p>Now, we are going to use Attributes.QueueArn (result from previous command) and TopicArn (from step 1.) and create a topic subscription:</p><pre>aws sns subscribe \<br> — topic-arn &quot;arn:aws:sns:us-east-1:254308114278:scheduler-topic&quot; \<br> — protocol &quot;sqs&quot; \<br> — notification-endpoint &quot;arn:aws:sqs:us-east-1:254308114278:service-queue&quot;<br></pre><p>And, that’s it. We just need to locate to service folder and run the service by executing npm run start. Our service endpoint will listen for the SQS messages and get triggered every time it receives message from Lambda function.</p><h3>6. Use Case</h3><p>One typical use case where we could use this kind of setup is a microservice architecture where we would setup central lambda scheduler for sending scheduled messages to our services. We already covered the scheduler setup, we just need to setup additional trigger events, topics, queues and services. Each service would read messages from a dedicated queue, and it would be triggered each time a message is published to the subscribed topic. It can be used to handle any kind of scheduled actions: generating reports, sending automatic emails, custom health monitoring etc.</p><p>As you can see, AWS Lambda is really powerful tool. Hope that this small example gave you one more idea on how to use lambdas in your projects.</p><p>Example code is located at <a href="https://github.com/mladenbolic/aws-lambda-scheduler">github</a>. Stay tuned for more articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=123c1d1ec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lombok @Data Improve your Code Coverage]]></title>
            <link>https://medium.com/@mladen.bolic/lombok-data-improve-your-code-coverage-a74fb624a72b?source=rss-313bdd56b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/a74fb624a72b</guid>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jacoco]]></category>
            <dc:creator><![CDATA[Mladen Bolic]]></dc:creator>
            <pubDate>Sun, 25 Feb 2018 10:11:33 GMT</pubDate>
            <atom:updated>2018-09-24T20:51:26.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FehrZMyV5_4U8NhjoGgDEQ.jpeg" /></figure><h3>Problem</h3><p>On my previous project we had a problem to achieve good code coverage with <a href="https://www.eclemma.org/jacoco/">Jacoco</a>. <a href="https://projectlombok.org/">Lombok</a> was used extensively on the project and each time we added new domain object we were loosing those precious code coverage percentages.</p><p>So what was happening?</p><p>We were using @lombok.Data for generating equals/hashCode/toString methods for Java beans. The problem was that code coverage tool was marking this methods as uncovered. So, instead of having plain Java bean with full code coverage, we ended up with around 15% coverage per Java bean. Adding new beans, just made already bad situation even worst.</p><h3>Solution</h3><p>Different solutions were proposed on how to fix this problem. One of them was using a 3rd party library to “cover” all equals/hashCode methods generated by Lombok. We’ve seen this solution beeing used on similar projects, but since we founded it was a dirty fix, we didn’t want to use it in our case. The solution we finally chose was actually very simple.</p><p>In <a href="https://github.com/jacoco/jacoco/releases/tag/v0.8.0">0.8.0 release</a>, Jacoco added support for filtering out all methods annotated with @lombok.Generated from their reports. The only thing we needed to do was to tell Lombok to add the @lombok.Generated annotation to its generated methods.</p><p>In order to fix the issue, we added lombok.config file to the root of our project. The file had the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/220c2914939a8a12f4f2cc858ebb1c69/href">https://medium.com/media/220c2914939a8a12f4f2cc858ebb1c69/href</a></iframe><ul><li>config.stopBubbling = true is telling Lombok that this is the root<br> directory and that it shouldn’t search parent directories for more<br> configuration files (you can have more than one Lombok config files<br> in different directories/packages).</li><li>lombok.addLombokGeneratedAnnotation = true is telling Lombok to add @lombok.Generated annotation to all generated methods.</li></ul><p>And that’s it. After applying the given changes, Jacoco was filtering out Lombok auto-generated methods, code coverage was back to normal, and everybody was happy again :)).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a74fb624a72b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>