Jekyll2020-11-02T13:39:20+00:00https://blog.thibaultjanbeyer.com/feed.xmlThibault Jan Beyerworks, design, development and random stuffUnderstanding Same Origin Policy & CORS2019-07-25T00:00:00+00:002019-07-25T00:00:00+00:00https://blog.thibaultjanbeyer.com/cors-cross-origin-web<p>I’ve been developing front-end applications all my life. Nevertheless, every time I experience a CORS issue, I feel pain. Pain because no one is really sure how to handle it. Today I’ll try to ease that pain for all of us!
CORS are tied to the Same Origin Policy which protects against a very specific type of attack.</p>
<h2 id="tldr">TL;DR</h2>
<blockquote>
<ul>
<li>
It is a front-end dev’s problem that can only be fixed by a backend dev
</li>
<li>
The Same Origin Policy is only enforced by the browsers (front-end)
</li>
<li>
CORS has to be enabled by on the server (back-end)
</li>
<li>
It is important that in the server response, the `Access-Control-Allow-Origin` header is set.
</li>
<li>
It is very important that in the browsers request headers the `Origin` header is set.
</li>
<li>
If you experience any issues with so called tainted content, check whether one of those headers is missing.
</li>
<li>
https://enable-cors.org/index.html is a website that explains how to enable CORS on most backend technologies.
</li>
</ul>
</blockquote>
<h2 id="toc">TOC</h2>
<h3 id="understanding">Understanding</h3>
<p>1 <a href="#what-the-f-is-cors-anyways">What the f* is CORS anyways?</a></p>
<ul>
<li>1.1. <a href="#same-origin-policy-sop">Same Origin Policy (SOP)</a></li>
<li>1.2. <a href="#how-is-the-same-origin-policy-useful">How is the Same Origin Policy useful?</a></li>
<li>1.3. <a href="#examples-of-the-same-origin-policy">Examples of the Same Origin Policy</a></li>
<li>1.4. <a href="#so-should-we-keep-enforcing-the-same-origin-policy">So should we keep enforcing the Same Origin Policy?</a></li>
</ul>
<h3 id="usage">Usage</h3>
<p>2 <a href="#cross-origin-resource-sharing-cors-to-the-rescue">Cross-Origin Resource Sharing (CORS) to the rescue!</a></p>
<ul>
<li>2.1. <a href="#when-is-cors-triggered">When is CORS triggered?</a></li>
<li>2.2. <a href="#what-requests-can-use-cors">What requests can use CORS?</a></li>
<li>2.3. <a href="#how-to-use-cors-correctly">How to use CORS correctly?</a></li>
<li>2.4. <a href="#what-headers-do-we-need">What Headers do we need?</a></li>
<li>2.5. <a href="#how-to-enable-cors-on-my-server">How to enable CORS on my Server?</a></li>
<li>2.6. <a href="#how-to-use-resources-like-images-videos-links-and-scripts-with-cors">How to use resources like images, videos, links and scripts with CORS?</a></li>
</ul>
<h3 id="avoiding">Avoiding</h3>
<p>3 <a href="#how-to-bypass-the-same-origin-policy-sop-and-avoid-cors">How to bypass the Same Origin Policy (SOP) and avoid CORS?</a></p>
<ul>
<li>3.1. <a href="#postmessage-communication">PostMessage Communication</a></li>
<li>3.2. <a href="#use-a-proxy">Use a proxy</a></li>
</ul>
<h3 id="end">End</h3>
<p>4 <a href="#further-reading">Further Reading</a><br />
5 <a href="#final-words">Final Words</a></p>
<h2 id="what-the-f-is-cors-anyways">What the f* is CORS anyways?</h2>
<p>To understand Cross-Origin Resource Sharing (CORS) we have to understand the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">Same-Origin Policy</a>:</p>
<h2 id="same-origin-policy-sop">Same Origin Policy (SOP)</h2>
<p>The Same-Origin Policy is a web-browsers’ standard that prevents malicious external scripts to access sensitive data from one web-page.
Generally it only permits a web-page to load data that comes from the same origin.
For example if a web-page on the origin <code class="language-plaintext highlighter-rouge">www.foo.com/bar</code> is requesting an image from <code class="language-plaintext highlighter-rouge">www.foo.com/image.png</code> it will work by default since the resource is on the same origin as the request comes from.
But, when <code class="language-plaintext highlighter-rouge">www.foo.com</code> loads resources from <code class="language-plaintext highlighter-rouge">www.baz.com</code> they will either be tainted (meaning they can be displayed but not read from in JavaScript) or forbidden completely by the same origin policy since <code class="language-plaintext highlighter-rouge">baz.com</code> is not the same origin as <code class="language-plaintext highlighter-rouge">foo.com</code>.
An origin is defined as a combination of <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Examples">URI scheme</a>, <a href="https://en.wikipedia.org/wiki/Hostname">domain</a>, and <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">port number</a>.</p>
<p>So, before CORS came into play, it was almost impossible to load resources from other web-pages. Now CORS is a mechanism that make this sharing possible. We’ll see how in a minute.</p>
<h3 id="how-is-the-same-origin-policy-useful">How is the Same Origin Policy useful?</h3>
<p>It’s a concept to isolate one website from another.
It is what stops for example Facebook accessing the data from your bank account.
<i class="hilite">This rule is enforced by the browser. If it’s not a browser, then the Same Origin Policy does not apply.</i></p>
<h3 id="examples-of-the-same-origin-policy">Examples of the Same Origin Policy</h3>
<h4 id="you-could-for-example-from-website-a-open-another-website-b-and-readmanipulate-its-content-like-so">You could for example from website A open another website B and read/manipulate its content like so:</h4>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// on www.hacker.com</span>
<span class="kd">const</span> <span class="nx">bank</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">open</span><span class="p">(</span><span class="dl">'</span><span class="s1">https://www.yourbank.com/transactions</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">right</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">bank</span><span class="p">.</span><span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">);</span> <span class="c1">// same origin “error”</span>
</code></pre></div></div>
<p>Here we are on the website hacker.com, this website opens a new browser tab for us which loads yourbank.com (suppose that’s the name of our bank).
Now suppose I’m logged in already, hacker.com could read all information of that page. Or worse, could send me to the banks official login page but capture my credentials on the way!</p>
<p>Luckily the Same Origin Policy prevents that. So the actual output will be an error similar to: <code class="language-plaintext highlighter-rouge">Error: Blocked a frame with origin "https://www.hacker.com/" from accessing a cross-origin frame</code>.
Which is a good example on how one website/window/origin is isolated from another by the Same Origin Policy.</p>
<h4 id="the-same-could-be-done-using-frames">The same could be done using frames:</h4>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"><!-- on www.hacker.com --></span>
<span class="nt"><frameset</span> <span class="na">cols=</span><span class="s">"50%,50%"</span><span class="nt">></span>
<span class="nt"><frame</span> <span class="na">name=</span><span class="s">"framea"</span> <span class="na">src=</span><span class="s">"https://www.hacker.com/hack"</span> <span class="nt">/></span>
<span class="nt"><frame</span> <span class="na">name=</span><span class="s">"frameb"</span> <span class="na">src=</span><span class="s">"https://www.yourbank.com/transactions"</span> <span class="nt">/></span>
<span class="nt"></frameset></span>
<span class="nt"><script></span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">framea</span><span class="p">.</span><span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">);</span> <span class="c1">// works</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">frameb</span><span class="p">.</span><span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">);</span> <span class="c1">// same origin “error”</span>
<span class="nt"></script></span>
</code></pre></div></div>
<p>Here is some ancient example of frames. This is how websites used to be ~15 years ago.
Although the same principles apply on <code class="language-plaintext highlighter-rouge">iframes</code>, which you are probably more familiar with.
Same as with example one, because of the Same Origin Policy the website hacker.com can only access the contents of <code class="language-plaintext highlighter-rouge">framea</code> (since it is on the same origin) but not <code class="language-plaintext highlighter-rouge">frameb</code>!</p>
<h4 id="images-video-css-and-js">Images, Video, CSS and JS:</h4>
<p>Any image, video, CSS and JS code <i class="hilite">can be loaded and executed from any other site but not read</i>. The image will be shown, the video will be shown and the CSS will be applied. However, you won’t be able to read the contents with JavaScript:</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"><!-- on www.hacker.com --></span>
<span class="nt"><link</span> <span class="na">rel=</span><span class="s">"stylesheet"</span> <span class="na">type=</span><span class="s">"text/css"</span> <span class="na">href=</span><span class="s">"hacker.css"</span> <span class="nt">/></span>
<span class="nt"><link</span>
<span class="na">rel=</span><span class="s">"stylesheet"</span>
<span class="na">type=</span><span class="s">"text/css"</span>
<span class="na">href=</span><span class="s">"https://www.yourbank.com/transactions.css"</span>
<span class="nt">/></span>
<span class="nt"><script></span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">styleSheets</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="nx">rules</span><span class="p">);</span> <span class="c1">// works</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">styleSheets</span><span class="p">[</span><span class="mi">1</span><span class="p">].</span><span class="nx">rules</span><span class="p">);</span> <span class="c1">// null (empty)</span>
<span class="nt"></script></span>
</code></pre></div></div>
<p>The same example applies to images, videos and JavaScript code. This is done to protect you in case there was any sensitive information in an image/video/css</p>
<h4 id="http-requests">HTTP Requests:</h4>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// on www.hacker.com</span>
<span class="nx">fetch</span><span class="p">(</span><span class="dl">'</span><span class="s1">https://hacker.com/info</span><span class="dl">'</span><span class="p">,</span> <span class="p">{</span> <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span> <span class="na">body</span><span class="p">:</span> <span class="dl">'</span><span class="s1">hi</span><span class="dl">'</span> <span class="p">});</span> <span class="c1">// works</span>
<span class="nx">fetch</span><span class="p">(</span><span class="dl">'</span><span class="s1">https://yourbank.com/transactions</span><span class="dl">'</span><span class="p">,</span> <span class="p">{</span> <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span> <span class="na">body</span><span class="p">:</span> <span class="dl">'</span><span class="s1">hi</span><span class="dl">'</span> <span class="p">});</span> <span class="c1">// does not</span>
</code></pre></div></div>
<p>Note that the request is actually happening: the browser sends the request to your bank, the browser will receive the response from your bank, but the browser will not let JavaScript access that response. You will get some kind of <code class="language-plaintext highlighter-rouge">No 'Access-Control-Allow-Origin' Headers present</code> error message instead.</p>
<p>As you can see, the Same Origin Policy is a set of rules implemented by the browsers that protect one web-page from others in the same browser. It isolated pages from one another.</p>
<h3 id="so-should-we-keep-enforcing-the-same-origin-policy">So should we keep enforcing the Same Origin Policy?</h3>
<p>It depends. While it might be another layer of security, I can totally aggree with <a href="https://www.reddit.com/r/Frontend/comments/cfpf5a/what_are_your_painpoints_with_cors_cross_origin/euchfph/">ttwinlakkes</a>:
most of the times I have had problems with it is with protected APIs that already have protections in place. It might be a good idea in general, but it is a nuisance if your only cross-origin resources are protected public endpoints.</p>
<p>As you can see it really depends on your use case: Enabling Cross Origin Request for all domains <strong>is not</strong> a security risc per se and can make total sense. Generally, <i class="hilite">for 99% of public APIs the Same Origin Policy makes absolutely no sense</i>.</p>
<h2 id="cross-origin-resource-sharing-cors-to-the-rescue">Cross-Origin Resource Sharing (CORS) to the rescue!</h2>
<p>With time came the conclusion that it is very often required to load resources from other origins.
For example, you might want to host your API endpoint on another origin than your web-app, i.e. <code class="language-plaintext highlighter-rouge">api.foo.com</code> vs <code class="language-plaintext highlighter-rouge">app.foo.com</code>.<br />
CORS is basically how you say “Do not apply the Same Origin Policy here”. I’ll explain exactly how in a bit.</p>
<h3 id="when-is-cors-triggered">When is CORS triggered?</h3>
<p>Whenever you make a HTTP Request to:</p>
<ul>
<li>a <em>different domain</em> (i.e. foo.com calls baz.com)</li>
<li>a <em>different subdomain</em> (i.e. bar.foo.com calls bat.baz.com)</li>
<li>a <em>different port</em> (i.e. foo.com calls foo.com:9000)</li>
<li>a <em>different protocol</em> (i.e. https://foo.com calls http://foo.com).</li>
</ul>
<h3 id="what-requests-can-use-cors">What requests can use CORS?</h3>
<ul>
<li>Any <code class="language-plaintext highlighter-rouge">XMLHttpRequest</code> or <code class="language-plaintext highlighter-rouge">Fetch</code> requests.</li>
<li>Web Fonts (as @font-face within CSS).</li>
<li>WebGL textures.</li>
<li>Images, Videos, Scripts and Links when the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes">crossorigin</a> attribute is set.</li>
</ul>
<h3 id="how-to-use-cors-correctly">How to use CORS correctly?</h3>
<p>CORS allows a site to “opt-in” to weaken SOP and allow external pages to access and read data.</p>
<ul>
<li>Sender sends a request with an <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin">origin</a> header.</li>
<li>Receiver answers with at least an <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin">Access-Control-Allow-Origin</a> header.</li>
</ul>
<h3 id="what-headers-do-we-need">What Headers do we need?</h3>
<h4 id="access-control-allow-origin"><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin">Access-Control-Allow-Origin</a></h4>
<p>Restricts which origins are allowed to make a request.
Use <code class="language-plaintext highlighter-rouge">*</code> to allow access from all origins or use a specific origin:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Access-Control-Allow-Origin: https://developer.mozilla.org
</code></pre></div></div>
<p><i class="hilite">If you require the client to pass authentication headers (e.g. cookies) the value <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials">can not be *</a> — it must be a fully qualified domain!</i></p>
<h4 id="access-control-allow-methods"><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods">Access-Control-Allow-Methods</a></h4>
<p>Which <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">HTTP Methods</a> are allowed to be made:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE
</code></pre></div></div>
<h4 id="access-control-allow-credentials"><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials">Access-Control-Allow-Credentials</a></h4>
<p>Only required if your server supports cookie auth.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Access-Control-Allow-Credentials: true
</code></pre></div></div>
<h4 id="more-access-control-headers">More access control headers:</h4>
<p>These are less common, still, here is the list:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers">Access-Control-Allow-Headers</a>
A comma separated list of headers your server will allow to get. Skip this if you’re ok with all request headers.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers">Access-Control-Expose-Headers</a>
A comma separated list indicating which headers can be exposed as part of the response.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers">Access-Control-Expose-Methods</a>
Response header indicates which headers can be exposed as part of the response.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age">Access-Control-Max-Age</a>
Response header indicates how long the results of a preflight request can be cached.</li>
</ul>
<p>For Requests:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers">Access-Control-Request-Headers</a>
Request header is used by browsers when issuing a preflight request, to let the server know which Headers will be used when the actual request is made.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Method">Access-Control-Request-Method</a>
Request header is used by browsers when issuing a preflight request, to let the server know which HTTP method will be used when the actual request is made.</li>
</ul>
<h3 id="how-to-enable-cors-on-my-server">How to enable CORS on my Server?</h3>
<p>The fabulous website <a href="https://enable-cors.org/server.html">enable-cors.org</a> has a list on how to enable CORS for Apache, nginx, PHP, Tomcat, Caddy, Meteor and many more.
For NodeJS you can either write them yourself or use this nice <a href="https://expressjs.com/en/resources/middleware/cors.html">express middleware</a>.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">express</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">express</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">app</span> <span class="o">=</span> <span class="nx">express</span><span class="p">();</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">((</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">next</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">res</span><span class="p">.</span><span class="nx">append</span><span class="p">(</span><span class="dl">'</span><span class="s1">Access-Control-Allow-Origin</span><span class="dl">'</span><span class="p">,</span> <span class="p">[</span><span class="dl">'</span><span class="s1">*</span><span class="dl">'</span><span class="p">]);</span>
<span class="nx">res</span><span class="p">.</span><span class="nx">append</span><span class="p">(</span>
<span class="dl">'</span><span class="s1">Access-Control-Allow-Methods</span><span class="dl">'</span><span class="p">,</span>
<span class="dl">'</span><span class="s1">GET,PUT,POST,DELETE,OPTIONS,PATCH</span><span class="dl">'</span>
<span class="p">);</span>
<span class="nx">next</span><span class="p">();</span>
<span class="p">});</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span><span class="dl">'</span><span class="s1">/</span><span class="dl">'</span><span class="p">,</span> <span class="k">async</span> <span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">res</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">ok</span><span class="dl">'</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">listen</span><span class="p">(</span><span class="mi">3000</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">Example app listening on port 3000!</span><span class="dl">'</span><span class="p">);</span>
<span class="p">});</span>
</code></pre></div></div>
<h3 id="how-to-use-resources-like-images-videos-links-and-scripts-with-cors">How to use resources like images, videos, links and scripts with CORS?</h3>
<p>In HTML, there is an attribute for that! It’s called <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes">crossorigin</a> and here is how you use it:</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><img</span> <span class="na">crossorigin=</span><span class="s">"anonymous"</span> <span class="na">src=</span><span class="s">"https://foo.com/img"</span> <span class="nt">/></span>
<span class="c"><!-- OR --></span>
<span class="nt"><img</span> <span class="na">crossorigin=</span><span class="s">"use-credentials"</span> <span class="na">src=</span><span class="s">"https://foo.com/img"</span> <span class="nt">/></span>
<span class="c"><!-- Also works with other resources: --></span>
<span class="nt"><script
</span><span class="na">crossorigin=</span><span class="s">"anonymous"</span>
<span class="na">src=</span><span class="s">"https://example.com/example-framework.js"</span>
<span class="nt">></script></span>
<span class="nt"><link</span> <span class="na">crossorigin=</span><span class="s">"use-credentials"</span> <span class="na">rel=</span><span class="s">"manifest"</span> <span class="na">href=</span><span class="s">"/app.webmanifest"</span> <span class="nt">/></span>
<span class="nt"><video</span>
<span class="na">crossorigin=</span><span class="s">"anonymous"</span>
<span class="na">src=</span><span class="s">"https://example.com/videofile.ogg"</span>
<span class="na">autoplay</span>
<span class="na">poster=</span><span class="s">"posterimage.jpg"</span>
<span class="nt">></video></span>
</code></pre></div></div>
<p>Note:</p>
<ul>
<li>If you load those resources without the crossorigin working, they are referred as <code class="language-plaintext highlighter-rouge">tainted</code>. I.e. a Cross Origin Image that was included without respecting CORS is referred as <code class="language-plaintext highlighter-rouge">Tainted Image</code> and its manipulation is restricted.</li>
<li>The Server still has to have CORS enabled and send the image with an <code class="language-plaintext highlighter-rouge">Access-Control-Allow-Credentials</code> Header</li>
<li>In some older browsers <a href="https://github.com/facebook/react/issues/14035">and in React</a> it is very important that the <code class="language-plaintext highlighter-rouge">crossorigin</code> attribute is set before the <code class="language-plaintext highlighter-rouge">src</code> attribute otherwise it might be ignored!</li>
</ul>
<h2 id="how-to-bypass-the-same-origin-policy-sop-and-avoid-cors">How to bypass the Same Origin Policy (SOP) and avoid CORS?</h2>
<h3 id="postmessage-communication">PostMessage Communication</h3>
<p>PostMessage allow sites to “opt-in” to remove SOP.</p>
<ul>
<li>Sender specifies where it sends to.</li>
<li>Receiver checks which origin it received the message from.</li>
</ul>
<h4 id="example">Example</h4>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Sender (parentsite)</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">frameA</span><span class="p">.</span><span class="nx">postMessage</span><span class="p">(</span><span class="nx">message</span><span class="p">,</span> <span class="dl">'</span><span class="s1">http://siteA.com</span><span class="dl">'</span><span class="p">);</span>
<span class="c1">// Receiver (siteA)</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">message</span><span class="dl">'</span><span class="p">,</span> <span class="nx">event</span> <span class="o">=></span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">origin</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">http://parentsite.com</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">wrong origin</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">innerText</span> <span class="o">=</span> <span class="nx">event</span><span class="p">.</span><span class="nx">data</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>
<p>However, the relationship has to match the origin of the receiver.
Read more: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage</p>
<h3 id="use-a-proxy">Use a proxy</h3>
<p>Since it is only the browser that enforces the SOP you can place a Server in the middle of your request:</p>
<ul>
<li>Sender sends the request a Server on the same origin or with CORS enabled</li>
<li>The Server redirects the request to the external recipient</li>
<li>The Server gets the response and passes it back to the Sender</li>
</ul>
<p>Why does it work? Because as described above, SOP doesn’t apply server-to-server communication, only to browser-to-server.</p>
<h4 id="example-1">Example</h4>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">proxy</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">express-http-proxy</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">app</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">express</span><span class="dl">'</span><span class="p">)();</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="dl">'</span><span class="s1">/proxy</span><span class="dl">'</span><span class="p">,</span> <span class="nx">proxy</span><span class="p">(</span><span class="dl">'</span><span class="s1">www.google.com</span><span class="dl">'</span><span class="p">));</span>
</code></pre></div></div>
<p>This is a super basic example of a basic Proxy server in NodeJS with express using <a href="https://www.npmjs.com/package/express-http-proxy">express-http-proxy</a>.
It takes any request to the <code class="language-plaintext highlighter-rouge">/proxy</code> endpoint and passes it through to <code class="language-plaintext highlighter-rouge">www.google.com</code>, returning the response to the caller.</p>
<h4 id="other-proxies">Other Proxies</h4>
<ul>
<li><a href="https://webpack.js.org/configuration/dev-server/#devserverproxy">Webpack has its own proxy included</a>.</li>
<li><a href="https://github.com/Rob--W/cors-anywhere/">Robwu has hosted a proxy for us</a>.</li>
</ul>
<h2 id="further-reading">Further Reading</h2>
<p>If you would like tho know more about CORS and SOP, I can recommend following resources for a deep dive:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing (CORS)</a> explained on MDN in detail.</li>
<li><a href="https://medium.com/@baphemot/understanding-cors-18ad6b478e2b">Understanding CORS</a> gives you another brief explanation on the topic and the headers.</li>
<li>The <a href="https://research.aurainfosec.io/same-origin-policy/">Aura Security Research Division article on SOP</a> goes deeper into the browser behavior with Cross Origin Requests.</li>
<li><a href="https://www.youtube.com/watch?v=zul8TtVS-64">1h OWASP video about Same Origin</a> OWASP is a great resource to learn about web security and in this video they explain the same origin policy in detail.</li>
</ul>
<h2 id="final-words">Final words</h2>
<p>Congratulations! You just learned all you have to know about CORS and SOP.</p>
<p>PS: don’t forget to share the knowledge and to follow me <a href="https://twitter.com/ThibaultBeyer">on twitter <i class="fab fa-twitter"></i></a> or via <a class="toggle-sidebar" data-a11y-dialog-show="subscribe-dialog" href="#site-sidebar">email <i class="fa fa-fw fa-columns"></i></a> if you liked this post :)</p>I’ve been developing frontends all my life. Nevertheless, every time I experience a CORS issue, I feel pain. Today I’ll try to ease that pain for all of us!A Quick guide to JavaScript Patterns2019-06-01T00:00:00+00:002019-06-01T00:00:00+00:00https://blog.thibaultjanbeyer.com/quick-guide-js-patterns<p>Here, I will give you a brief explanation on patterns I stumble across. I will find a real life reference for each pattern and explain it in such an easy way that is easy to remember. That give you a quick and good overview about complex topics. This page is perfect to bookmark and review in case you need to refresh your knowledge. It is also a living document, by that I mean that I will constantly update this article always explaining new patterns I find in the simplest possible way. I’ll also add resources in case you want to dig deeper. Without further ado, let’s have a look at the JavaScript Patterns. Enjoy reading!</p>
<h2 id="toc">TOC</h2>
<h3 id="creational-patterns">Creational Patterns:</h3>
<ol>
<li><a href="#singleton-pattern">Singleton Pattern</a></li>
<li><a href="#prototype-pattern">Prototype Pattern</a></li>
<li><a href="#module-design-pattern">Module Design Pattern</a></li>
</ol>
<h3 id="structural-patterns">Structural Patterns:</h3>
<ol>
<li><a href="#decorator-pattern">Decorator Pattern</a></li>
<li><a href="#adapter-pattern">Adapter Pattern</a></li>
</ol>
<h3 id="behavioral-patterns">Behavioral Patterns</h3>
<ol>
<li><a href="#observer-pattern">Observer Pattern</a></li>
<li><a href="#publish-subscribe-messaging-pattern">Publish Subscribe Messaging Pattern</a></li>
<li><a href="#mediator-pattern">Mediator Pattern</a></li>
</ol>
<h3 id="end">End</h3>
<ol>
<li><a href="#further-reading">Further Reading</a></li>
<li><a href="#final-words">Final Words</a></li>
</ol>
<p><em>Please note that all JS code examples are just examples. They can be written in a variety of ways. How you write the pattern is up to you. A Pattern is just an abstract idea.</em></p>
<h2 id="singleton-pattern">Singleton Pattern</h2>
<p>The singleton pattern is the simple concept of restricting the instantiating of a class to one object/instance.</p>
<h3 id="real-life-example">Real Life Example</h3>
<p>Singletons are everywhere, basically everything that is accessed by multiple persons and only available once.
Let’s say that in your office there is only one printer that everyone can use. Then that printer might be called a singleton.</p>
<p><img class="aligncenter size-full" src="/assets/patterns/printer.jpg" alt="Huge letterpress printing machine" /></p>
<h3 id="javascript-example">JavaScript Example</h3>
<ul>
<li>In redux the state could be called a singleton since there is only one state tree available.</li>
</ul>
<p>A singleton could look something like this:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nx">Singleton</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">()</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">Singleton</span><span class="p">.</span><span class="nx">instance</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">Singleton</span><span class="p">.</span><span class="nx">instance</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1">// Initialize object</span>
<span class="k">return</span> <span class="nx">Singleton</span><span class="p">.</span><span class="nx">instance</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1">// Properties & Methods</span>
<span class="p">}</span>
<span class="kd">const</span> <span class="nx">instance</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Singleton</span><span class="p">();</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">instance</span><span class="p">;</span>
</code></pre></div></div>
<p><em>Please note that this and all further JS code examples are just examples. They can be written in a variety of ways. How you write the pattern is up to you. A Pattern is just an abstract idea.</em></p>
<h3 id="pros-and-cons-of-the-singleton-pattern">Pros and Cons of the Singleton Pattern</h3>
<h4 id="pros">Pros</h4>
<ul>
<li>Instance control: Singleton prevents other objects from instantiating their own copies of the Singleton object, ensuring that all objects access the single instance.</li>
<li>Flexibility: Since the class controls the instantiating process, the class has the flexibility to change the instantiating process.</li>
<li>Easy to implement: Easy to create, and we could use it anywhere for the lifetime of the app The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton.</li>
</ul>
<h4 id="cons">Cons</h4>
<ul>
<li>They are a global mutable shared state. Their state is automatically shared across the entire app, and bugs can often start occurring when that state changes unexpectedly.</li>
<li>The relationships between Singletons and the code that depends on them is usually not very well-defined. Since Singletons are so convenient and easy to access — using them extensively usually leads to very hard to maintain “spaghetti code” that doesn’t have clear separations between objects.</li>
<li>Managing their life-cycle can be tricky. Since Singletons are alive during the entire lifespan of an application, managing them can be really hard. This also makes code that relies on Singletons really hard to test, since you can’t easily start from a “clean slate” in each test case.</li>
</ul>
<h2 id="prototype-pattern">Prototype Pattern</h2>
<p>It’s a pattern where we bind variables and methods to our object structure which can be initiated <em>N</em> times. The object to be created is defined by a prototype instance (blueprint to be replicated or learned from) which is cloned to produce new objects.</p>
<h3 id="real-life-example-1">Real Life Example</h3>
<p>It’s quite difficult to find a good real life example for such a pattern. Maybe the blueprint for a construction work could be called a prototype pattern.</p>
<p><img class="aligncenter size-full" src="/assets/patterns/blueprint.jpg" alt="a blueprint for construction work" /></p>
<h3 id="javascript-example-1">JavaScript Example</h3>
<ul>
<li>Prototypical example:</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// blueprint</span>
<span class="kd">function</span> <span class="nx">MyClass</span><span class="p">(</span><span class="nx">bar</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">foo</span> <span class="o">=</span> <span class="nx">bar</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">MyClass</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">baz</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">bat</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">foo</span><span class="p">,</span> <span class="nx">bat</span><span class="p">);</span>
<span class="p">};</span>
<span class="c1">// Initiation</span>
<span class="kd">const</span> <span class="nx">myClass</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MyClass</span><span class="p">(</span><span class="dl">'</span><span class="s1">bar</span><span class="dl">'</span><span class="p">);</span> <span class="c1">// create new instance</span>
<span class="nx">myClass</span><span class="p">.</span><span class="nx">baz</span><span class="p">(</span><span class="dl">'</span><span class="s1">bat</span><span class="dl">'</span><span class="p">);</span> <span class="c1">// => console.log("bar", "bat");</span>
<span class="nx">myClass</span><span class="p">.</span><span class="nx">foo</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">lol</span><span class="dl">'</span><span class="p">;</span> <span class="c1">// => console.log("bar", "bat");</span>
<span class="nx">myClass</span><span class="p">.</span><span class="nx">baz</span><span class="p">(</span><span class="dl">'</span><span class="s1">what?</span><span class="dl">'</span><span class="p">);</span> <span class="c1">// => console.log("lol", "what?");</span>
</code></pre></div></div>
<ul>
<li>ES6 Class example:</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nx">MyClass</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">(</span><span class="nx">bar</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">foo</span> <span class="o">=</span> <span class="nx">bar</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">baz</span><span class="p">(</span><span class="nx">bat</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">foo</span><span class="p">,</span> <span class="nx">bat</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="c1">// Initiation is the same as above</span>
</code></pre></div></div>
<p>This pattern also has a <strong>revealing variant</strong> which just means that not all methods are exposed:</p>
<ul>
<li>Revealing Prototypical example:</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// blueprint</span>
<span class="kd">function</span> <span class="nx">MyClass</span><span class="p">(</span><span class="nx">bar</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">foo</span> <span class="o">=</span> <span class="nx">bar</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">MyClass</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">bat</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="kr">private</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">you don’t see me</span><span class="dl">'</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">privateFunc</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=></span> <span class="dl">'</span><span class="s1">you also don’t see me</span><span class="dl">'</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">baz</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">bat</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">foo</span><span class="p">,</span> <span class="nx">bat</span><span class="p">);</span>
<span class="p">};</span>
<span class="k">return</span> <span class="p">{</span> <span class="nx">baz</span> <span class="p">};</span>
<span class="p">};</span>
<span class="kd">const</span> <span class="nx">myClass</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MyClass</span><span class="p">(</span><span class="dl">'</span><span class="s1">bar</span><span class="dl">'</span><span class="p">);</span> <span class="c1">// create new instance</span>
<span class="nx">myClass</span><span class="p">.</span><span class="nx">baz</span><span class="p">(</span><span class="dl">'</span><span class="s1">bat</span><span class="dl">'</span><span class="p">);</span> <span class="c1">// => console.log("bar", "bat");</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">myClass</span><span class="p">.</span><span class="kr">private</span><span class="p">);</span> <span class="c1">// => undefined</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">myClass</span><span class="p">.</span><span class="nx">privateFunc</span><span class="p">());</span> <span class="c1">// => TypeError … is not a function</span>
</code></pre></div></div>
<p>As you can see, the <code class="language-plaintext highlighter-rouge">private</code> variable is not exposed while <code class="language-plaintext highlighter-rouge">baz</code> is.</p>
<ul>
<li>Revealing Class example:</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nx">MyClass</span> <span class="p">{</span>
<span class="err">#</span><span class="kr">private</span><span class="p">;</span>
<span class="kd">constructor</span><span class="p">(</span><span class="nx">bar</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">foo</span> <span class="o">=</span> <span class="nx">bar</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="err">#</span><span class="kr">private</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">you don’t see me</span><span class="dl">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">baz</span><span class="p">(</span><span class="nx">bat</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">foo</span><span class="p">,</span> <span class="nx">bat</span><span class="p">);</span>
<span class="p">}</span>
<span class="err">#</span><span class="nx">privateFunc</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="dl">'</span><span class="s1">you also don’t see me</span><span class="dl">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p><em>Note: this is a new technology and you might need a polyfill for this to work.</em></p>
<h3 id="pros-and-cons-of-the-prototype-pattern">Pros and Cons of the Prototype Pattern</h3>
<h4 id="pros-1">Pros</h4>
<ul>
<li>You can clone objects without coupling to their concrete classes.</li>
<li>You can get rid of repeated initialization code in favor of cloning pre-built prototypes.</li>
<li>You can produce complex objects more conveniently.</li>
</ul>
<h4 id="cons-1">Cons</h4>
<ul>
<li>Cloning complex objects that have circular references might be very tricky.</li>
</ul>
<h2 id="module-design-pattern">Module Design Pattern</h2>
<p>Is the pattern of organizing code into modules that allow <em>encapsulation</em> to have a private scope giving access to selected methods and classes to the outside.<br />
There is a variant to this pattern which is called the <strong>revealing module design pattern</strong>. Which is basically the same but instead of exposing the whole object or nothing, you just expose only some selected methods.</p>
<h3 id="real-life-example-2">Real Life Example</h3>
<p>A real life example might be an elevator button. To us, it just exposes one method (for example floor 10) but it might rely on more private functionality in the background which is handled when pressed (close door/go to 10/open door).</p>
<p><img class="aligncenter size-full" src="/assets/patterns/elevator.jpg" alt="floor buttons in an elevator" /></p>
<h3 id="javascript-example-2">JavaScript Example</h3>
<p>There are different ways we can use to achieve the modular pattern:</p>
<ul>
<li>IIFE (Immediately-invoked Function Expression)</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">myModule</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">//...</span>
<span class="k">return</span> <span class="p">{</span>
<span class="c1">//...</span>
<span class="p">};</span>
<span class="p">})();</span>
</code></pre></div></div>
<ul>
<li>AMD Modules</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">define</span><span class="p">(</span>
<span class="dl">'</span><span class="s1">MyModule</span><span class="dl">'</span><span class="p">,</span>
<span class="p">[</span><span class="dl">'</span><span class="s1">RequiredModule</span><span class="dl">'</span><span class="p">],</span>
<span class="kd">function</span> <span class="p">(</span><span class="nx">RequiredModule</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">{</span>
<span class="c1">//...</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="p">);</span>
</code></pre></div></div>
<ul>
<li>CommonJS Modules</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// in uppercase.js</span>
<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">str</span> <span class="o">=></span> <span class="nx">str</span><span class="p">.</span><span class="nx">toUpperCase</span><span class="p">();</span>
<span class="c1">// somewhere else.js</span>
<span class="kd">const</span> <span class="nx">uppercaseModule</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">uppercase.js</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">uppercaseModule</span><span class="p">(</span><span class="dl">'</span><span class="s1">test</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div></div>
<ul>
<li>Native JavaScript Modules</li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// in uppercase.js</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">str</span> <span class="o">=></span> <span class="nx">str</span><span class="p">.</span><span class="nx">toUpperCase</span><span class="p">();</span>
<span class="c1">// somewhere else.js</span>
<span class="k">import</span> <span class="nx">uppercaseModule</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">uppercase.js</span><span class="dl">'</span><span class="p">;</span>
<span class="nx">uppercaseModule</span><span class="p">(</span><span class="dl">'</span><span class="s1">test</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div></div>
<h3 id="pros-and-cons-of-the-module-design-pattern">Pros and Cons of the Module Design Pattern</h3>
<h4 id="pros-2">Pros</h4>
<ul>
<li>Encapsulation. Which prevents variable or method names to clash and override each other.</li>
</ul>
<h4 id="cons-2">Cons</h4>
<ul>
<li>Revealing module pattern keeps private methods out of scope. That is both, good and bad. It can be good because you have the power to limit users to only use public methods. It can be bad because the user has no possibility to extend some private functionality.</li>
</ul>
<h2 id="decorator-pattern">Decorator Pattern</h2>
<p>Decorator is a pattern that lets you add new behaviors to objects by placing them inside special wrapper objects containing those new behaviors.<br />
The decorator pattern is sometimes also named Wrapper.<br />
In python for example a decorator is a function that takes another function, extending the behavior of the latter function without explicitly modifying it.</p>
<h3 id="real-life-example-3">Real Life Example</h3>
<ul>
<li>In react we find this pattern quite often. <a href="https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md">withRouter</a> from React-Router is an example.</li>
</ul>
<p>Wearing clothes is an example. Cold? Wrap yourself in a sweater. Rain? Put on a raincoat. These garments “extend” your basic behavior but aren’t part of you. You can take them off whenever you don’t need it.</p>
<p><img class="aligncenter size-full" src="/assets/patterns/snow.jpg" alt="It snows in the city, people walk around wearing big coats" /></p>
<h3 id="javascript-example-3">JavaScript Example</h3>
<ul>
<li>Without <a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841">decorator syntax</a></li>
</ul>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">admin</span><span class="p">(</span><span class="nx">target</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">target</span><span class="p">.</span><span class="nx">role</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">admin</span><span class="dl">'</span><span class="p">;</span>
<span class="k">return</span> <span class="nx">target</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">class</span> <span class="nx">User</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="nx">role</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">user</span><span class="dl">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">say</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">`User: </span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">name</span><span class="p">}</span><span class="s2">, </span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">role</span><span class="p">}</span><span class="s2">`</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="kd">const</span> <span class="nx">user</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">User</span><span class="p">(</span><span class="dl">'</span><span class="s1">me</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">user</span><span class="p">.</span><span class="nx">say</span><span class="p">();</span> <span class="c1">// User: me, user</span>
<span class="kd">const</span> <span class="nx">admin</span> <span class="o">=</span> <span class="nx">admin</span><span class="p">(</span><span class="k">new</span> <span class="nx">User</span><span class="p">(</span><span class="dl">'</span><span class="s1">him</span><span class="dl">'</span><span class="p">));</span>
<span class="nx">user</span><span class="p">.</span><span class="nx">say</span><span class="p">();</span> <span class="c1">// User: him, admin</span>
</code></pre></div></div>
<h3 id="pros-and-cons-of-the-decorator-pattern">Pros and Cons of the Decorator Pattern</h3>
<h4 id="pros-3">Pros</h4>
<ul>
<li>Extend an object’s behavior without making a new subclass.</li>
<li>Add or remove responsibilities from an object at run time.</li>
<li>Combine several behaviors by wrapping an object into multiple decorators.</li>
<li>Single Responsibility Principle. You can divide a monolithic class that implements many possible variants of behavior into several smaller classes.</li>
</ul>
<h4 id="cons-3">Cons</h4>
<ul>
<li>Difficult to test the base object when there are a lot of wrappers around.</li>
<li>Hard to remove specific wrapper from the wrappers stack.</li>
<li>It’s hard to implement a decorator in such a way that its behavior doesn’t depend on the order in the decorators stack.</li>
<li>The initial configuration code of layers might look pretty ugly.</li>
</ul>
<h2 id="adapter-pattern">Adapter Pattern</h2>
<p>Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.</p>
<h3 id="real-life-example-4">Real Life Example</h3>
<p>A good example for this is a universal power charger travel adapter.</p>
<p><img class="aligncenter size-full" src="/assets/patterns/adapter.jpg" alt="Travel adapter to charge your devices" /></p>
<h3 id="javascript-example-4">JavaScript Example</h3>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">getData</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// returns XML</span>
<span class="k">return</span> <span class="k">new</span> <span class="nx">DOMParser</span><span class="p">().</span><span class="nx">parseFromString</span><span class="p">(</span><span class="s2">`<foo>bar</foo>`</span><span class="p">,</span> <span class="dl">'</span><span class="s1">text/xml</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">useData</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// needs JSON</span>
<span class="kd">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">xmlToJsonAdapter</span><span class="p">(</span><span class="nx">getData</span><span class="p">());</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">used: </span><span class="dl">'</span><span class="p">,</span> <span class="nx">data</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="nx">foo</span><span class="p">);</span> <span class="c1">// => used: bar</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">xmlToJsonAdapter</span><span class="p">(</span><span class="nx">xml</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// converts XML to JSON</span>
<span class="k">return</span> <span class="p">[...</span><span class="nx">xml</span><span class="p">.</span><span class="nx">childNodes</span><span class="p">].</span><span class="nx">map</span><span class="p">(</span><span class="nx">node</span> <span class="o">=></span> <span class="p">({</span>
<span class="p">[</span><span class="nx">node</span><span class="p">.</span><span class="nx">tagName</span><span class="p">]:</span> <span class="nx">node</span><span class="p">.</span><span class="nx">textContent</span><span class="p">,</span>
<span class="p">}));</span>
<span class="p">}</span>
</code></pre></div></div>
<h3 id="pros-and-cons-of-the-adapter-pattern">Pros and Cons of the Adapter Pattern</h3>
<h4 id="pros-4">Pros</h4>
<ul>
<li>Single Responsibility Principle. You can separate the interface or data conversion code from the primary business logic of the program.</li>
<li>Open/Closed Principle. You can introduce new types of adapters into the program without breaking the existing client code.</li>
</ul>
<h4 id="cons-4">Cons</h4>
<ul>
<li>Complexity increases because you need to introduce a set of new interfaces and classes.</li>
</ul>
<h2 id="observer-pattern">Observer Pattern</h2>
<p>The Observer Pattern is basically a part called <em>subject</em> that maintains a list of so called <em>observers</em> and notifies them of changes.</p>
<h3 id="real-life-example-5">Real Life Example</h3>
<p>A newspaper subscription could be an observer pattern. People can be added to a list, when there is a new newspaper coming out they will go through the list and send out the newspaper to each of the observers/subscribers.</p>
<p><img class="aligncenter size-full" src="/assets/patterns/observer.jpg" alt="Man reading a newspaper" /></p>
<h3 id="javascript-example-5">JavaScript Example</h3>
<ul>
<li>Talking about redux, the <code class="language-plaintext highlighter-rouge">connect</code> method is an example of an observer pattern.</li>
<li>Angulars two ways binding is also an example of an observer pattern.</li>
</ul>
<p>An observer pattern could be something like that:</p>
<p class="codepen" data-height="265" data-theme-id="dark" data-default-tab="js,result" data-user="ThibaultJanBeyer" data-slug-hash="BevZNL" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Singleton Pattern Example">
<span>See the Pen <a href="https://codepen.io/ThibaultJanBeyer/pen/BevZNL/">
Singleton Pattern Example</a> by Thibault Jan Beyer (<a href="https://codepen.io/ThibaultJanBeyer">@ThibaultJanBeyer</a>)
on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async="" src="https://static.codepen.io/assets/embed/ei.js"></script>
<h3 id="pros-and-cons-of-the-observer-pattern">Pros and Cons of the Observer Pattern</h3>
<h4 id="pros-5">Pros</h4>
<ul>
<li>Decouples observers from the initiator.</li>
<li>Send data to many other objects in a very efficient manner.</li>
<li>You can add and remove observers at anytime.</li>
<li>Built in, in some languages/frameworks</li>
</ul>
<h4 id="cons-5">Cons</h4>
<ul>
<li>Coupling between the subject and its observers</li>
<li>Execution order is not deterministic</li>
</ul>
<h2 id="publish-subscribe-messaging-pattern">Publish Subscribe Messaging Pattern</h2>
<p>Is a somewhat loosely coupled observer pattern: a sender of messages called <em>publisher</em> sends <em>topics</em> (messages) to the classes without knowing who is subscribing. <em>Subscribers</em> listen to <em>topics</em> and only receive messages relevant to that <em>topic</em> without knowing about the sender.</p>
<h3 id="real-life-example-6">Real Life Example</h3>
<p>A suggestion or complaint box could be an example. Another example might be an information window, the <em>publisher</em> places informational messages into the window then anyone interested can read those messages.</p>
<p><img class="aligncenter size-full" src="/assets/patterns/message-wall.jpg" alt="Man reading a news from newspapers hanging on the wall" /></p>
<h3 id="javascript-example-6">JavaScript Example</h3>
<p>A Pub/Sub pattern in JavaScript could be something like this:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">topic</span> <span class="o">=</span> <span class="p">{};</span>
<span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">q</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">topics</span> <span class="o">=</span> <span class="p">{},</span>
<span class="nx">subUid</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="nx">q</span><span class="p">.</span><span class="nx">subscribe</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">topic</span><span class="p">,</span> <span class="nx">func</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">topics</span><span class="p">[</span><span class="nx">topic</span><span class="p">])</span> <span class="p">{</span>
<span class="nx">topics</span><span class="p">[</span><span class="nx">topic</span><span class="p">]</span> <span class="o">=</span> <span class="p">[];</span>
<span class="p">}</span>
<span class="kd">var</span> <span class="nx">token</span> <span class="o">=</span> <span class="p">(</span><span class="o">++</span><span class="nx">subUid</span><span class="p">).</span><span class="nx">toString</span><span class="p">();</span>
<span class="nx">topics</span><span class="p">[</span><span class="nx">topic</span><span class="p">].</span><span class="nx">push</span><span class="p">({</span>
<span class="na">token</span><span class="p">:</span> <span class="nx">token</span><span class="p">,</span>
<span class="na">func</span><span class="p">:</span> <span class="nx">func</span><span class="p">,</span>
<span class="p">});</span>
<span class="k">return</span> <span class="nx">token</span><span class="p">;</span>
<span class="p">};</span>
<span class="nx">q</span><span class="p">.</span><span class="nx">publish</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">topic</span><span class="p">,</span> <span class="nx">args</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">topics</span><span class="p">[</span><span class="nx">topic</span><span class="p">])</span> <span class="p">{</span>
<span class="k">return</span> <span class="kc">false</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">subscribers</span> <span class="o">=</span> <span class="nx">topics</span><span class="p">[</span><span class="nx">topic</span><span class="p">],</span>
<span class="nx">len</span> <span class="o">=</span> <span class="nx">subscribers</span> <span class="p">?</span> <span class="nx">subscribers</span><span class="p">.</span><span class="nx">length</span> <span class="p">:</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">while</span> <span class="p">(</span><span class="nx">len</span><span class="o">--</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">subscribers</span><span class="p">[</span><span class="nx">len</span><span class="p">].</span><span class="nx">func</span><span class="p">(</span><span class="nx">topic</span><span class="p">,</span> <span class="nx">args</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">},</span> <span class="mi">0</span><span class="p">);</span>
<span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">};</span>
<span class="nx">q</span><span class="p">.</span><span class="nx">unsubscribe</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">token</span><span class="p">)</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">m</span> <span class="k">in</span> <span class="nx">topics</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">topics</span><span class="p">[</span><span class="nx">m</span><span class="p">])</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="nx">j</span> <span class="o">=</span> <span class="nx">topics</span><span class="p">[</span><span class="nx">m</span><span class="p">].</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</span> <span class="nx">j</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">topics</span><span class="p">[</span><span class="nx">m</span><span class="p">][</span><span class="nx">i</span><span class="p">].</span><span class="nx">token</span> <span class="o">===</span> <span class="nx">token</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">topics</span><span class="p">[</span><span class="nx">m</span><span class="p">].</span><span class="nx">splice</span><span class="p">(</span><span class="nx">i</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>
<span class="k">return</span> <span class="nx">token</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">return</span> <span class="kc">false</span><span class="p">;</span>
<span class="p">};</span>
<span class="p">})(</span><span class="nx">topic</span><span class="p">);</span>
<span class="c1">// can be subscribed to like this:</span>
<span class="nx">topic</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="dl">'</span><span class="s1">api/user/refresh</span><span class="dl">'</span><span class="p">,</span> <span class="nx">user</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">user</span><span class="p">.</span><span class="nx">name</span><span class="p">));</span>
<span class="c1">// topics can be published like that</span>
<span class="nx">topic</span><span class="p">.</span><span class="nx">publish</span><span class="p">(</span><span class="dl">'</span><span class="s1">api/user/refresh</span><span class="dl">'</span><span class="p">,</span> <span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">'</span><span class="s1">foo</span><span class="dl">'</span> <span class="p">});</span> <span class="c1">// this would trigger a console.log("foo");</span>
<span class="nx">topic</span><span class="p">.</span><span class="nx">publish</span><span class="p">(</span><span class="dl">'</span><span class="s1">api/user/refresh</span><span class="dl">'</span><span class="p">,</span> <span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">'</span><span class="s1">bar</span><span class="dl">'</span> <span class="p">});</span> <span class="c1">// this would trigger a console.log("bar");</span>
</code></pre></div></div>
<h3 id="pros-and-cons-of-the-pubsub-pattern">Pros and Cons of the Pub/Sub Pattern</h3>
<h4 id="pros-6">Pros</h4>
<ul>
<li>Publishers are loosely coupled to subscribers, and need not even know of their existence.</li>
<li>Scalability: parallel operation, message caching, …</li>
</ul>
<h4 id="cons-6">Cons</h4>
<ul>
<li>No way to know if the message was successfully received.</li>
<li>A publisher in a pub/sub system may assume that a subscriber is listening, when in fact it is not.</li>
</ul>
<h2 id="mediator-pattern">Mediator Pattern</h2>
<p>A centralized controller to which components communicate instead of directly to each other.</p>
<h3 id="real-life-example-7">Real Life Example</h3>
<p>An airport control tower: all planes communicate to the tower, the tower then gives instructions to the planes based on the input of the various planes. They don’t talk directly to each other.</p>
<p><img class="aligncenter size-full" src="/assets/patterns/airport-tower.jpg" alt="Airport control tower with planes flying around" /></p>
<h3 id="javascript-example-7">JavaScript Example</h3>
<p>Here is a chatroom example as mediator pattern:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nx">Chatroom</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">member</span> <span class="o">=</span> <span class="p">{};</span>
<span class="p">}</span>
<span class="nx">register</span><span class="p">(</span><span class="nx">member</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">member</span><span class="p">[</span><span class="nx">member</span><span class="p">.</span><span class="nx">name</span><span class="p">]</span> <span class="o">=</span> <span class="nx">member</span><span class="p">;</span>
<span class="nx">member</span><span class="p">.</span><span class="nx">chatroom</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
<span class="k">return</span> <span class="k">this</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">send</span><span class="p">(</span><span class="nx">message</span><span class="p">,</span> <span class="k">from</span><span class="p">,</span> <span class="nx">to</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">to</span><span class="p">)</span> <span class="k">return</span> <span class="nx">to</span><span class="p">.</span><span class="nx">receive</span><span class="p">(</span><span class="nx">message</span><span class="p">,</span> <span class="k">from</span><span class="p">);</span> <span class="c1">// direct message</span>
<span class="nb">Object</span><span class="p">.</span><span class="nx">values</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">member</span><span class="p">)</span> <span class="c1">// broadcast message</span>
<span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">member</span> <span class="o">=></span> <span class="nx">member</span><span class="p">.</span><span class="nx">receive</span><span class="p">(</span><span class="nx">message</span><span class="p">,</span> <span class="k">from</span><span class="p">));</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="kd">class</span> <span class="nx">Member</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="nx">room</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">send</span><span class="p">(</span><span class="nx">message</span><span class="p">,</span> <span class="nx">to</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">room</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="nx">message</span><span class="p">,</span> <span class="k">this</span><span class="p">,</span> <span class="nx">to</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">receive</span><span class="p">(</span><span class="nx">message</span><span class="p">,</span> <span class="k">from</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">from</span><span class="p">.</span><span class="nx">name</span> <span class="o">+</span> <span class="dl">'</span><span class="s1"> to </span><span class="dl">'</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">: </span><span class="dl">'</span> <span class="o">+</span> <span class="nx">message</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="kd">const</span> <span class="nx">john</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Participant</span><span class="p">(</span><span class="dl">'</span><span class="s1">John</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">doe</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Participant</span><span class="p">(</span><span class="dl">'</span><span class="s1">Doe</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">chatroom</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Chatroom</span><span class="p">();</span>
<span class="nx">chatroom</span><span class="p">.</span><span class="nx">register</span><span class="p">(</span><span class="nx">john</span><span class="p">).</span><span class="nx">register</span><span class="p">(</span><span class="nx">doe</span><span class="p">);</span>
<span class="nx">john</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">All you need is love.</span><span class="dl">'</span><span class="p">);</span> <span class="c1">// broadcast to everyone</span>
<span class="nx">john</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">I love you Doe.</span><span class="dl">'</span><span class="p">,</span> <span class="nx">doe</span><span class="p">);</span> <span class="c1">// private message to doe</span>
</code></pre></div></div>
<p>In this case the chatroom is the mediator between its members.</p>
<h3 id="pros-and-cons-of-the-mediator-pattern">Pros and Cons of the Mediator Pattern</h3>
<h4 id="pros-7">Pros</h4>
<ul>
<li>Single Responsibility Principle.</li>
<li>Open/Closed Principle. You can introduce new mediators without having to change the actual components.</li>
<li>You can reduce coupling between various components.</li>
<li>You can reuse individual components easily.</li>
</ul>
<h4 id="cons-7">Cons</h4>
<ul>
<li>Over time a mediator can evolve into an insanely big and complex Object.</li>
</ul>
<h2 id="further-reading">Further Reading</h2>
<p>If you liked the patterns I can recommend following resources for a deep dive:</p>
<ul>
<li><a href="https://refactoring.guru/design-patterns">Design Patterns explained by refactoring guru</a> which is very well illustrated.</li>
<li><a href="https://addyosmani.com/resources/essentialjsdesignpatterns/book/">Learning JavaScript Design Patterns. A book by Addy Osmani</a> which is very detailed.</li>
<li><a href="https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know">Scotch Tutorial on 4 Patterns</a></li>
<li><a href="https://www.dofactory.com/javascript/design-patterns">Do Factory</a> they have a lot of patterns, unfortunately the code examples are mostly bad (because they want you to buy their book)</li>
</ul>
<h2 id="final-words">Final words</h2>
<p>Congratulations! You just learned the basics from the most used design patterns in JavaScript. This should give you an understanding of code architecture and how to improve your code. Considering patterns truly makes you stand apart from most devs and improves your code quality.</p>
<p>PS: don’t forget to share the knowledge and to follow me <a href="https://twitter.com/ThibaultBeyer">on twitter <i class="fab fa-twitter"></i></a> or via <a class="toggle-sidebar" data-a11y-dialog-show="subscribe-dialog" href="#site-sidebar">email <i class="fa fa-fw fa-columns"></i></a> if you liked this post :)</p>TL;DR ! Today, JavaScript Design Patterns. What is it? Explained with JavaScript examples, real life examples and considering pros and cons.A Quick guide to the JavaScript Event Loop (Browser)2019-05-24T00:00:00+00:002019-05-24T00:00:00+00:00https://blog.thibaultjanbeyer.com/quick-guide-js-event-loop<p>I finally found some time to write a new article. Lately I had a talk about IT and I realized that while I know most of the topics and how they work, I have really hard times explaining them. So I looked online on how others do it and only found very huge and deep articles on those topics. So, what I want to achieve is to create very brief explanation that give you a quick and good overview about complex topics. These articles are perfect to bookmark and review in case you need to refresh your knowledge. I’ll also add resources in case you want to dig deeper. Today we will have a look at the JavaScript event loop in the browser. Enjoy reading!</p>
<h2 id="toc">TOC</h2>
<ol>
<li><a href="#how-does-the-event-loop-look-like">How does the event loop look like?</a></li>
<li><a href="#what-is-a-stack">What is a Stack?</a></li>
<li><a href="#what-is-a-queue">What is a Queue?</a></li>
<li><a href="#1-the-call-stack">1. The Call Stack</a></li>
<li><a href="#2-the-heap">2. The Heap</a></li>
<li><a href="#2b-web-api">2b. Web API</a></li>
<li><a href="#3-the-message-queue">3. The Message Queue</a></li>
<li><a href="#non-blocking">(non) Blocking</a></li>
<li><a href="#what-comes-first-example">What comes first (example)</a></li>
<li><a href="#best-practice">Best Practice</a></li>
<li><a href="#further-reading">Further Reading</a></li>
</ol>
<h2 id="how-does-the-event-loop-look-like">How does the event loop look like?</h2>
<p>Here is my representation of the event loop:</p>
<p><img class="aligncenter size-full" src="/assets/event-loop/JavaScript-Event-Loop.png" alt="The JavaScript Browser Event Loop" /></p>
<p>As you can see there is a loop list, a heap which is just an allocation of memory somewhere there also resides the Web API that will handle our asynchronous activities. Then we have a stack where the event loop will place and handle our synchronous calls and a message queue where the asynchronous callback handlers will be placed.</p>
<p>Let me explain some concepts here quickly:</p>
<h2 id="what-is-a-stack">What is a Stack?</h2>
<p>A stack is a conceptual structure in which elements can be placed. The concept of a stack is <code class="language-plaintext highlighter-rouge">FILO</code> which means that the first element which you place in a stack is the last element that will get out of the stack.<br />
A real world example of a Stack would be a PEZ Dispenser (if you don’t know what that is, I found a <a href="https://www.youtube.com/watch?v=YIAN6eKltsA">PEZ video tutorial</a> online).</p>
<p><img class="aligncenter size-full" src="/assets/event-loop/PEZ-dispenser-star-wars.png" alt="Star Wars PEZ dispenser" style="height: 300px" /></p>
<h2 id="what-is-a-queue">What is a Queue?</h2>
<p>I think that you are all aware about what a queue is. It is a conceptual structure following the <code class="language-plaintext highlighter-rouge">FIFO</code> concept, which means that the first element which you place in a queue is the first element that comes out.<br />
There are plenty real world examples of queues. For example when you do your groceries, the line in which you stay for the checkout is a queue.</p>
<p><img class="aligncenter size-full" src="/assets/event-loop/People-waiting-in-line-with-shopping-baskets-at-grocery-store.jpg" alt="People waiting in line at a grocery store" /></p>
<h2 id="1-the-call-stack">1. The Call Stack</h2>
<p>You JavaScript code will be parsed one after another and added to the Stack. Let’s suppose you have following code:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">foo</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="mi">1</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">bar</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">second</span> <span class="o">=</span> <span class="nx">foo</span><span class="p">();</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">second</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">bar</span><span class="p">();</span>
</code></pre></div></div>
<p>Considering our representation above, this is what would happen when executing the code:</p>
<ul>
<li>Start code:<br />
<code class="language-plaintext highlighter-rouge">[main()]</code></li>
<li>Push <code class="language-plaintext highlighter-rouge">bar()</code> to the stack:<br />
<code class="language-plaintext highlighter-rouge">[bar(), main()]</code></li>
<li>Push <code class="language-plaintext highlighter-rouge">console.log(1)</code> to the stack:<br />
<code class="language-plaintext highlighter-rouge">[log(1), bar(), main()]</code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">console.log(1)</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[bar(), main()]</code> => log 1</li>
<li>Push <code class="language-plaintext highlighter-rouge">foo()</code> to the stack:<br />
<code class="language-plaintext highlighter-rouge">[foo(), bar(), main()]</code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">foo()</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[bar(), main()]</code> => return 2</li>
<li>Push <code class="language-plaintext highlighter-rouge">console.log(second)</code> to the stack:<br />
<code class="language-plaintext highlighter-rouge">[log(2), bar(), main()]</code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">console.log(2)</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[bar(), main()]</code> => log 2</li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">bar()</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[main()]</code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">main()</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[]</code></li>
<li>Exit the stack</li>
</ul>
<p>Here is an excerpt from a <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">talk on the JS Conf</a> which explains it quite well:</p>
<p><img class="aligncenter size-full" src="/assets/event-loop/stack-example-jsconf.gif" alt="Stack Example JSConf" /></p>
<h2 id="2-the-heap">2. The heap</h2>
<p>The heap is just an unstructured region of memory that is used for execution.</p>
<h2 id="2b-web-api">2b. Web API</h2>
<p>Are handling the asynchronous operations, they are responsible to hold timeouts, promises etc. until they get resolved and push the callback function to the message queue. More on that below:</p>
<h2 id="3-the-message-queue">3. The Message Queue</h2>
<p>When we use an asynchronous method, the web-api will take care of its delay time and place it into the queue as soon as it is resolved.<br />
When the Call Stack is empty, the message queue is resolved.</p>
<p>Let’s consider this example:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
<span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="nx">callback</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span>
<span class="p">},</span> <span class="mi">5000</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
</code></pre></div></div>
<p>For comparison, I will represent the Web API as brackets <code class="language-plaintext highlighter-rouge">()</code> and the queue like this <code class="language-plaintext highlighter-rouge"><></code>. This is by no means how a queue or API looks like.</p>
<ul>
<li>Start code:<br />
<code class="language-plaintext highlighter-rouge">[main()]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Push <code class="language-plaintext highlighter-rouge">console.log(1)</code> to the stack:<br />
<code class="language-plaintext highlighter-rouge">[log(1), main()]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">console.log(1)</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[main()]</code> => log 1 / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Give <code class="language-plaintext highlighter-rouge">setTimeout</code> to the Web API:<br />
<code class="language-plaintext highlighter-rouge">[main()]</code> / <code class="language-plaintext highlighter-rouge">(setTimeout[5s])</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Push <code class="language-plaintext highlighter-rouge">console.log(2)</code> to the stack:<br />
<code class="language-plaintext highlighter-rouge">[log(2), main()]</code> / <code class="language-plaintext highlighter-rouge">(setTimeout[5s])</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">console.log(2)</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[main()]</code> => log 2 / <code class="language-plaintext highlighter-rouge">(setTimeout[5s])</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">main</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Exit the stack</li>
<li>The Web API timeout is over. It enqueues the <code class="language-plaintext highlighter-rouge">callback</code> function to the Message Queue:<br />
<code class="language-plaintext highlighter-rouge">[]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><callback()></code></li>
<li><em>As the Stack is empty</em>, the message queue is processes and dequeues <code class="language-plaintext highlighter-rouge">callback</code> by pushing it to the Stack:<br />
<code class="language-plaintext highlighter-rouge">[callback()]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Push <code class="language-plaintext highlighter-rouge">console.log(3)</code> to the stack:<br />
<code class="language-plaintext highlighter-rouge">[log(3), callback()]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">console.log(3)</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[callback()]</code> => log 3 / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Pop (resolve) <code class="language-plaintext highlighter-rouge">callback</code> from the stack:<br />
<code class="language-plaintext highlighter-rouge">[]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Exit the stack</li>
<li>The queue is empty:<br />
<code class="language-plaintext highlighter-rouge">[]</code> / <code class="language-plaintext highlighter-rouge">()</code> / <code class="language-plaintext highlighter-rouge"><></code></li>
<li>Exit the queue</li>
</ul>
<p>Here is an excerpt from a <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">talk on the JS Conf</a> which explains it quite well:</p>
<p><img class="aligncenter size-full" src="/assets/event-loop/queue-example-jsconf.gif" alt="Queue Example JSConf" /></p>
<h2 id="non-blocking">(non) Blocking</h2>
<p>As mentioned before that refers to JavaScript handling events sequentially. The call stack can not be interrupted while running. The Queue is only processes when the call stack is empty. The timer on the setTimeout is just the minimum time to wait, it can take longer to be executed since it has to wait until the call stack is empty and all entries that are in the queue before the timeout de-queued.<br />
So the calls executed on the web-api are referred as <code class="language-plaintext highlighter-rouge">non-blocking</code>. Anything executed on the call stack is considered <code class="language-plaintext highlighter-rouge">blocking</code> as it prevents everything else from being executed. For example if you have a long-running function on the call stack, it will even prevent user interaction like even clicking on buttons on the page. An infinite loop for example will block the execution of anything else forever and thus crash the browser tab.</p>
<h2 id="what-comes-first-example">What comes first (example)</h2>
<p>So now having all this knowledge, what will be executed first?</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
<span class="nx">setImmediate</span><span class="p">(()</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">immediate</span><span class="dl">"</span><span class="p">));</span>
<span class="nx">requestAnimationFrame</span><span class="p">(()</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">animation</span><span class="dl">"</span><span class="p">));</span>
<span class="nx">requestIdleCallback</span><span class="p">(()</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">idle</span><span class="dl">"</span><span class="p">));</span>
<span class="nx">setInterval</span><span class="p">(()</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">interval</span><span class="dl">"</span><span class="p">));</span>
<span class="nx">setTimeout</span><span class="p">(()</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">timeout</span><span class="dl">"</span><span class="p">));</span>
<span class="nb">Promise</span><span class="p">.</span><span class="nx">resolve</span><span class="p">().</span><span class="nx">then</span><span class="p">(()</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">promise resolved</span><span class="dl">"</span><span class="p">));</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
</code></pre></div></div>
<p>Ok, that was mean because I added some <code class="language-plaintext highlighter-rouge">requestIdleCallback</code> and <code class="language-plaintext highlighter-rouge">setImmediate</code> which are non-standard. The output is actually:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
2
promise resolved
immediate
animation
interval
timeout
idle
interval interval interval etc…
</code></pre></div></div>
<p>Which surprised me because based on the specs immediate should come later. But it’s currently non-standard and only implemented in Internet Explorer.
Apart from that, the promises are resolved immediately and handled before the timeout or interval.
Timeout is usually handled last (except for <code class="language-plaintext highlighter-rouge">requestIdleCallback</code> which really waits until nothing else is running), so as you understand the timeout milliseconds is just a minimum wait time and is not always accurate.</p>
<h2 id="best-practice">Best Practice</h2>
<ul>
<li>Try to avoid long-running (blocking) methods by reducing the time complexity (for example avoiding unnecessary loops).</li>
<li>If the long-running method can not be avoided, delegate it to a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">web worker</a>. Those will be executed in background threads and thus not block the main execution.</li>
<li>Avoid infinite loops. This might sound like a no-brainer but it’s still worth mentioning, and I think that now you understand why infinite loops are crashing the web-app.</li>
<li>Avoid ducktaping using the message queue. Often timing issues are solved by placing methods to the message queue using setTimeout. However, this will quickly lead to an unmaintainable code base because it is hard to predict what is in the message queue in what order. Rather find and fix the root cause.</li>
<li>Don’t use a timeout as a callback. For example, when you want to remove a div element after playing an animation (for example slowly putting the opacity to 0 to fade it out). You should rather use genuine callbacks like <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onanimationend">onanimationend</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/ontransitionend">ontransitionend</a> because <a href="#non-blocking">as we learned</a>, the setTimeout will not always be accurate in terms of time.</li>
</ul>
<h2 id="further-reading">Further reading</h2>
<p>I hope that this brief overview could give you a solid understanding of the JS Event Loop. If you’re feeling like you want to dig deeper, here are some articles I recommend on the topic:</p>
<ul>
<li>I can really recommend checking out the full <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">talk by Philip Roberts on YouTube</a>. I was at the JS-Conf in person and was quite impressed on how well he explained the topic.</li>
<li>You’ll find an on the point explanation of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">Concurrency Model and the Event Loop on MDN</a> as well.</li>
<li><a href="https://flaviocopes.com/javascript-event-loop/#blocking-the-event-loop">Flavio Copes</a> digs a bit deeper in the subject then I did.</li>
<li>For the NodeJS event loop, while it is similar at the core, it will still be treated a bit differently. I can recommend <a href="https://jsblog.insiderattack.net/event-loop-and-the-big-picture-nodejs-event-loop-part-1-1cb67a182810">Deepals 6 article series</a> which is very detailed.</li>
</ul>
<p>Thank you for reading and feel free to ask any question or let me know if you found any mistake.</p>
<p>PS: don’t forget to share the knowledge and to follow me <a href="https://twitter.com/ThibaultBeyer">on twitter <i class="fab fa-twitter"></i></a> or via <a class="toggle-sidebar" data-a11y-dialog-show="subscribe-dialog" href="#site-sidebar">email <i class="fa fa-fw fa-columns"></i></a> if you liked this post :)</p>TL;DR ! The JavaScript event loop. What is it? Explained in a nutshell.Migrating a Wordpress blog to Jekyll only 4 steps2018-12-29T00:00:00+00:002018-12-29T00:00:00+00:00https://blog.thibaultjanbeyer.com/migrating-wordpress-to-jekyll-blog<p>WordPress is all nice and stuff but when all you need is just a clean place to write content, Jekyll is the better tooling!
However, most developers, like myself, are stuck with a very old WordPress installation on their servers.
Worry not my friends, in this article, I’ll walk you 1 by 1 through the steps required to replace your WordPress blog with Jekyll.</p>
<h2 id="why-not-to-use-wordpress">Why not to use Wordpress.</h2>
<p>WordPress has some huge downsides. Here is what I’ve found most frustrating:</p>
<ul>
<li>You’ll have to back up your WordPress every week because sometimes it will break for no good reason.</li>
<li>WordPress can be hacked and will be hacked.</li>
<li>To protect against hacks you’ll have to update your WordPress now and then, which is always a high risk operation since it might break your installation.</li>
<li>WordPress is slow af.</li>
</ul>
<p>So as you can see it’s mostly about maintenance and the time you have to put into non-relevant things.</p>
<h2 id="what-is-jekyll-">What is jekyll ?</h2>
<p>Jekyll is a static site generator based on ruby. Meaning, you give it content and it will create some static pages HTML for you.
The nice thing is that GitHub Pages support Jekyll natively. That leads us to the following advantages:</p>
<ul>
<li>Hosting on GitHub Pages is Free.</li>
<li>Jekyll serves static Pages, which can’t be hacked.</li>
<li>You don’t have to update Jekyll.</li>
<li>Static Pages are lightning fast.</li>
</ul>
<p>Basically, in the long run, that will save a lot of time.</p>
<h2 id="how-to-move-from-wordpress-to-jekyll-">How to move from Wordpress to Jekyll ?</h2>
<h3 id="1-backup-wordpress--setup-jekyll">1. Backup Wordpress & Setup Jekyll</h3>
<h4 id="backup-wordpress">Backup Wordpress</h4>
<p>First of all, you should backup your current WordPress installation in case something goes wrong.
There are plenty of available backup tools in the WordPress plugins section. Have a look.
Personally, I used Blackguard for no specific reason.
Go to “Backups” and run a new full backup. Then download the backup files and place them somewhere safe. This will be our fallback if anything goes wrong.</p>
<h4 id="setup-jekyll">Setup Jekyll</h4>
<p>Setting up Jekyll is very easy. You can set up everything by hand or use a preset.
Because I’m lazy, I used a pre-configured Jekyll made by Barry Clask which is called <a href="https://github.com/barryclark/jekyll-now">Jekyll-now</a>. Setting that one up is quite easy:</p>
<ul>
<li>Fork the repo.</li>
<li>Follow the <a href="https://github.com/barryclark/jekyll-now#local-development">local development guide</a></li>
<li>You can now run your blog locally using ‘Jekyll serve’
That’s it.</li>
</ul>
<p><em>PS: If you want to set up everything on your own, you can read up the process on <a href="http://jekyllrb.com">Jekyllrb.com</a>.</em></p>
<h3 id="2-import-content-from-wordpress">2. Import content from Wordpress</h3>
<p>Now here comes the tricky part. All posts on the topic suggest to use Ben Balters <a href="https://github.com/benbalter/wordpress-to-jekyll-exporter">wordpress-to-jekyll-exporter</a> plugin. However, that one did not work for me, as unfortunately it does not seem support the latest version of WordPress.
Luckily, our friends at Jekyll wrote their own scripts to achieve just that. Head over to the <a href="https://import.jekyllrb.com/docs/home/">documentation on Jekyll Import</a>.
As I did not have ssh access to my shared host (I know it’s crap but it is so damn cheap), I used the <a href="https://import.jekyllrb.com/docs/wordpressdotcom/">Wordpress.com importer</a>. The Process is also very easy:</p>
<ul>
<li>Install Jekyll importer with ‘gem install jekyll-import’ (use ‘sudo gem install …’ if it is complaining about rights)</li>
<li>Run the importer:</li>
</ul>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ruby <span class="nt">-rubygems</span> <span class="nt">-e</span> <span class="s1">'require "jekyll-import";
JekyllImport::Importers::WordpressDotCom.run({
"source" => "wordpress.xml",
"no_fetch_images" => false,
"assets_folder" => "assets"
})'</span>
</code></pre></div></div>
<p>Usually, when you first call it, you’ll get errors about missing dependencies. Just install whatever missing by doing ‘gem install NAME’ (replace the name with the name of the missing dependency).</p>
<p>That will import all your WordPress content. For me, it put all my images in a new folder called ‘assets’ and all my posts as HTML into the <code class="language-plaintext highlighter-rouge">_posts</code> folder.</p>
<p>Now you can run ‘jekyll serve’ all your posts should be then. Neat, right?</p>
<p>Sure it’s probably not 100% clean but it takes a lot of work away already. You should check your site for the broken image link, sometimes when your pictures have special characters the importer was not able to download them. Also, for me, unfortunately, the ‘excerpt’ was missing on every post, which I had to re-add manually. While doing that, I also cleaned out the unnecessary ‘meta’ part which was added to every post.</p>
<h3 id="3-setting-everything-up">3. Setting everything up</h3>
<h4 id="add-pagination">Add pagination</h4>
<p>From here, adding pagination is straight forward. You can use the provided <a href="https://jekyllrb.com/docs/pagination/">jekyll-paginate</a></p>
<h4 id="add-a-search">Add a search</h4>
<p>I used the <a href="https://www.npmjs.com/package/simple-jekyll-search">simple-jekyll-search</a> JavaScript plugin.</p>
<h4 id="fix-all-links-and-add-excerpts">Fix all links and add excerpts</h4>
<p>This was the most time-consuming thing as I had to go through all the blog-posts, check the links for websites and images, update those links accordingly.</p>
<p>Same thing for the excerpts: open each blog post and add an introducing description.</p>
<h4 id="add-related-posts">Add related posts</h4>
<p>Well here is the catch. The related posts by Jekyll are not really related to the article, it’s more like just showing the latest posts you wrote. So to add some mix to it, I combined the latest posts with some random posts, here is the magic code snippet:</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><ul</span> <span class="na">class=</span><span class="s">"related_posts"</span><span class="nt">></span>
{% for post in site.related_posts limit: 4 %} {% if forloop.index
> 2 %} {% assign random = site.time | date: '%s%N' | modulo:
site.posts.size %} {% assign post = site.posts[random] %} {%
endif %}
<span class="nt"><li</span> <span class="na">class=</span><span class="s">"related_post"</span><span class="nt">></span>
<span class="nt"><a</span> <span class="na">href=</span><span class="s">""</span><span class="nt">></span>
{% if post.image %}
<span class="nt"><img</span>
<span class="na">src=</span><span class="s">""</span>
<span class="na">alt=</span><span class="s">""</span>
<span class="na">class=</span><span class="s">"posts__img"</span>
<span class="nt">/></span>
{% endif %}
<span class="nt"><h3</span> <span class="na">class=</span><span class="s">"title"</span><span class="nt">></span>{{ post.title }}<span class="nt"></h3></span>
<span class="nt"></a></span>
<span class="nt"></li></span>
{% endfor %}
<span class="nt"></ul></span>
</code></pre></div></div>
<p>This will add 2 latest posts + 2 random posts.</p>
<h4 id="email-subscriptions">Email Subscriptions</h4>
<p>That’s also something I had to do from scratch since I used a WordPress specific plugin before. For my Jekyll blog, I decided to use <a href="https://mailchimp.com/">mailchimp</a> for a very simple reason: comparing it with other products, MailChimp did offer the biggest free plan and I did not want to pay just to save email addresses.</p>
<h4 id="comments">Comments</h4>
<p>Since Jekyll is only a static site generator, you can only use third party commenting systems. I went for <a href="https://disqus.com/">Disqus</a> because it’s already provided in the <a href="https://github.com/barryclark/jekyll-now">Jekyll Now</a> setup.
Disqus even offers a possibility to <a href="https://help.disqus.com/import-export-and-syncing/importing-comments-from-wordpress">import your WordPress comments</a>.</p>
<h3 id="4-redirects">4. Redirects</h3>
<p>So on WordPress, the URL for posts was ‘/portfolio/post’. However, with Jekyll, the path is now ‘/post’ without the portfolio part. Since Jekyll does not run on any server, you have two options for redirects.
Either you set up a redirect on your domain name provider or you use some JavaScript hack.
I chose to set up a <a href="https://support.cloudflare.com/hc/en-us/articles/200172286-How-do-I-perform-URL-forwarding-or-redirects-with-Cloudflare-">permanent redirect on Cloudflare</a> but you can also go with the front-end hack and here is the straight forward snipped to used:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="nx">location</span><span class="p">.</span><span class="nx">href</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="dl">"</span><span class="s2">/portfolio/</span><span class="dl">"</span><span class="p">)</span> <span class="o">></span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="nx">location</span><span class="p">.</span><span class="nx">href</span> <span class="o">=</span> <span class="nx">location</span><span class="p">.</span><span class="nx">href</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="sr">/</span><span class="se">\/</span><span class="sr">portfolio/g</span><span class="p">,</span> <span class="dl">""</span><span class="p">);</span>
</code></pre></div></div>
<p>Which checks if there is the <code class="language-plaintext highlighter-rouge">/portfolio/</code> part in the URL and just removes it. (not recommended, rather try setting up a permanent redirect as mentioned above)</p>
<h3 id="further-improvements">Further improvements</h3>
<h4 id="theming">Theming</h4>
<p>Obviously, the theme of your blog can not be copied 1 by 1 since WordPress and Jekyll are two fundamentally different tools.
Luckily there are tons of <a href="http://jekyllthemes.org/">free Jekyll themes</a>, as well as <a href="https://jekyllthemes.io/">paid themes</a> out there, ready for you to download.
For my part, as I like to style things myself, I quickly copied the Theming of my WordPress Theme myself using writing some SASS.</p>
<h4 id="custom-email-address">Custom Email Address</h4>
<p>I chose to get rid of my custom email address <code class="language-plaintext highlighter-rouge">@thibaultjanbeyer.com</code>, just because I have too many addresses. But you don’t have to get rid of yours when changing DNS provider. The best solution is to use the <a href="https://www.zoho.com/mail/help/email-hosting-with-zoho.html">free custom domain email from Zoho Mail</a> I use that service for several other projects and it is the most reliable free option.</p>
<h2 id="last-words">Last words</h2>
<p>That’s about it. Now, the blog is running on Jekyll instead of WordPress. Hopefully you don’t even notice the difference or if so, only because it’s better now :)
I hope that I could help someone who is thinking of leaving WordPress. Don’t get me wrong, it’s work. But it’s worth it.</p>
<p><button data-a11y-dialog-show="subscribe-dialog" type="button" class="metalink">Subscribe</button> to my blog if you found this article useful. Thank you =)</p>Wordpress is all nice and stuff but when all you need is just a clean place to write content, Jekyll is the better tooling!Building an interactive SPA for BMW2018-10-03T00:00:00+00:002018-10-03T00:00:00+00:00https://blog.thibaultjanbeyer.com/building-an-interactive-dealerlocator-for-bmw<blockquote>Type: Professional<br />
For: BMW Digital<br />
My Role: Frontend-Developer<br />
Languages: HTML, SCSS, JavaScript (Angular)</blockquote>
<p>During my time at Hi-ReS! I worked on BMW Digital Stage 2. While it was very interesting to writing new components and improving old components for the general BMW Websites and Shops. I learned to work on a large-scale company with a gigantic scale client (BMW has over 25 Markets including right to left languages such as Arabic) which was very interesting.</p>
<p>The most rewarding part however was to write<span class="background-details"> their new single page application called “Dealer Locator” using AngularJS Framework. I teamed up with <a href="http://www.frankleue.de/">Frank Leue</a>. Together, we created the <a href="https://www.bmw.de/de/fastlane/bmw-partner.html#/dlo/DE/de/BMW_BMWM">Dealer Locator</a>, a rich single page application written in Angular which helps customer find the nearest BMW dealer with ease</span>. We had a<span class="background-details"> strong focus on simplicity and user experience. Users can search for BMW dealers based on their location, on the dealers name or just by using the map. They can start a navigation, call the dealer directly, set it as their favorite, and filter the search by specific features. The user can also share url links that are direct pointers to any place in the app.
</span></p>
<ul>
<li><span class="background-details">Works perfectly on any screen size & browser (IE9)
</span></li>
<li>Features Dealer-Clustering</li>
<li>Start Navigation or contact dealer</li>
<li>Set specific dealer as your default favorite/default</li>
<li>Map/List representation work seamlessly together</li>
<li>Deep-Linking (user can share url to specifics positions in the app)</li>
</ul>
<p>Basic usage:</p>
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/ob1bR5bUEGk?rel=0&controls=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="allowfullscreen"></iframe>
<p>Find by name:</p>
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/4Hi-zWWQZJ4?rel=0&controls=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="allowfullscreen"></iframe>
<p>(as you can see, when there are multiple results for a query you’ll get suggestions)</p>
<p>Find near me:</p>
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/AnQjgti74uE?rel=0&controls=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="allowfullscreen"></iframe>
<p>Mobile view:</p>
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/P-SLVaEueTI?rel=0&controls=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="allowfullscreen"></iframe>
<p>URL sharing:</p>
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/4Z1N1RSL1kw?rel=0&controls=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="allowfullscreen"></iframe>
<p>You can play the dealerlocator yourself on any BMW website. For example, Germany: <a href="https://www.bmw.de/de/fastlane/bmw-partner.html">BMW.de </a></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer; top: 1470px; left: 20px;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer; top: 774px; left: 20px;">Save</span></p>Here is a free origami stile font for y’allVorablesen, an Online Book Community2016-12-28T00:00:00+00:002016-12-28T00:00:00+00:00https://blog.thibaultjanbeyer.com/vorablesen-an-online-book-community<blockquote>Type: Professional<br />
For: <a href="https://www.edenspiekermann.com/">Edenspiekermann_</a><br />
My Role: Frontend-Developer, UX Design and UX Research<br />
Languages: HTML, SCSS, JavaScript (ES6), Ruby on Rails, Git</p></blockquote>
<p>Back from <a href="http://blog.thibaultjanbeyer.com/portfolio/all-good-things-come-to-an-end-cape-town-6/" data-cke-saved-href="http://blog.thibaultjanbeyer.com/portfolio/all-good-things-come-to-an-end-cape-town-6/">South Africa</a>, I worked several months for <a href="https://www.edenspiekermann.com/" data-cke-saved-href="https://www.edenspiekermann.com/">Edenspiekermann_</a> on <a href="https://www.vorablesen.de" data-cke-saved-href="https://www.vorablesen.de">Vorablesen</a>. It’s an online book community. <a href="https://www.vorablesen.de" data-cke-saved-href="https://www.vorablesen.de">Vorablesen</a> offers book lovers many activities. Discover early titles, share opinions and the chance to win unreleased titles. There is also an easy to use points system allowing you to claim books immediately.</p>
<p>Besides severely influencing the total look and feel I heavily worked on these topics:</p>
<ul>
<li>Design and Development of the sign-up process.</li>
<li>Design and Development of the onboarding.</li>
<li>Extensive qualitative and quantitative (2400 users) researched.</li>
<li>Conduct user testings to check the usability of features.</li>
</ul>
<p>Have a look at the <a href="http://www.vorablesen.de" data-cke-saved-href="http://www.vorablesen.de">Vorablesen Website</a> (English version coming soon) and these screens:</p>
<p><a href="https://www.vorablesen.de/buecher/sweetgirl">Book Details Page</a>:</p>
<p><img class="aligncenter size-full wp-image-2907" src="/assets/website.jpg" alt="vorablesen website screen book-details-page" width="800" height="800" /></p>
<p><a href="https://www.vorablesen.de/willkommen">Onboarding</a>:</p>
<p><a href="https://www.vorablesen.de/willkommen"><img class="aligncenter wp-image-2909 size-large" src="/assets/Screen-Shot-2016-12-25-at-11.55.27-1024x552.png" alt="Vorablesen onboarding page" width="809" height="436" /></a></p>
<p><a href="https://www.vorablesen.de/willkommen"><img class="aligncenter wp-image-2910 size-large" src="/assets/Screen-Shot-2016-12-25-at-11.55.39-1024x559.png" alt="Vorablesen Onboarding page 2" width="809" height="442" /></a></p>
<p><a href="https://www.vorablesen.de/users/sign_in">Registration</a>:</p>
<p><a href="https://www.vorablesen.de/users/sign_in"><img class="aligncenter wp-image-2908 size-large" src="/assets/Screen-Shot-2016-12-25-at-11.56.09-1024x555.png" alt="vorablesen – login page" width="809" height="438" /></a></p>
<p>Colors:</p>
<p><img class="aligncenter size-large wp-image-2916" src="/assets/Screen-Shot-2016-12-25-at-12.40.29-1024x426.png" alt="vorablesen – colors" width="809" height="337" /></p>
<p>Landingpage | Book Details Page | Userpage:</p>
<p><a href="https://www.vorablesen.de/"><img class="aligncenter wp-image-2915 size-full" src="/assets/Desktop-HD.png" alt="Vorablesen Screens" width="2231" height="5298" /></a></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer; top: 1470px; left: 20px;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer; top: 774px; left: 20px;">Save</span></p>creating an online book community. My Role, Frontend-Developer, UX Design and UX Researcher.The untold stories of 20162016-12-15T00:00:00+00:002016-12-15T00:00:00+00:00https://blog.thibaultjanbeyer.com/the-untold-stories-of-2016<p>Hello dear reader, this year happened so much, that I did not find time to write an update earlier. Here is one that gives a brief overview on things that happened this year.</p>
<p>So, I started the year with an internship at <a href="https://www.edenspiekermann.com/">edenspeakermann_</a>, a great, forward thinking agency where I met <a href="https://twitter.com/martzoukos">Spiros</a> and <a href="http://hugogiraudel.com/">Hugo Giraudel</a> among many others very inspiring people. I worked as UX researcher, digital designer and front-end developer. I learned the agile and component-based work-style and it triggered my love for beautiful, modern, accessible and user-oriented websites.</p>
<p><a href="http://www.learn-accessibility.org/"><img class="aligncenter wp-image-2898 size-medium" src="/assets/687474703a2f2f692e696d6775722e636f6d2f314f57707341552e706e67-388x400.png" alt="Learn Accessibility" width="388" height="400" /></a></p>
<p>After that internship I finished my studies. My final thesis was <a href="http://www.learn-accessibility.org/">learn-accessibility.org</a> a website filling a gap in web-development, teaching accessibility: how to make websites accessible for everyone, what to consider and why/how to sell accessibility to the client. 6 Month of research and coding earned quite a recognition. I won 3 awards: Gold at the <a href="http://www.annual-multimedia.de/">annual multimedia</a> awards, Silver at the <a href="http://www.w3award.com/">w3 Awards</a> and a special award from the agency <a href="http://grey.com/germany">Grey</a> that honored our universities best works. I’ll write more about that project once the trophies/goodies arrive.</p>
<p><img class="aligncenter wp-image-2897 size-medium" src="/assets/Screen-Shot-2016-12-15-at-12.22.01-395x400.png" alt="Serious coding @ Hackathon Bonn" width="395" height="400" /></p>
<p>I also participated in a Big-Data <a href="https://en.wikipedia.org/wiki/Hackathon">Hackathon</a> in Bonn where we tried to write a tool in <a href="http://clojure.org/">clojure</a> that would play audio, based on your local weather data. As no member of the group used clojure before, it was fun to learn that very powerful language and we <a href="https://github.com/ThibaultJanBeyer/cloudify">kinda managed to get something going</a> but the time frame was too short for a working prototype. If I was to give this another shot, I would probably use <a href="http://gibber.mat.ucsb.edu/">gibber</a>. If you don’t know gibber, watch this video of gibbers founder live coding:</p>
<p>[embed]https://youtu.be/uly7DgtfRKI[/embed]</p>
<p>After my studies, I moved places: from the small town Bonn, former capital city of Germany, to the big & forward thinking city Berlin, current capital city of Germany and started working as interactive developer for <a href="http://hi-res.de/de/">Hi-ReS!</a>, where I developed a dealer locator app in Angular for <a href="https://www.bmwgroup.com/en.html">BMW</a>. I learned to work with Angular in a business scale and started to write unit tests using <a href="https://jasmine.github.io/">Jasmine</a>, <a href="http://karma-runner.github.io/1.0/index.html">Karma</a> and some automation with <a href="http://webdriver.io/">Selenium</a>.</p>
<pre lang="text"><code> _ __ _
__| |_ __ __ _ __ _ /\ \ \__| |_ __ ___ _ __
/ _` | '__/ _` |/ _` |/ \/ / _` | '__/ _ \| '_ \
| (_| | | | (_| | (_| / /\ | (_| | | | (_) | |_) |
\__,_|_| \__,_|\__, \_\ \/ \__,_|_| \___/| .__/
|___/ |_|
</code></pre>
<p>I recently started to work on some “secret” project together with Thomas, founder of <a href="http://swll.webflow.io/">SWLL</a>, extremely intelligent and a very good friend of mine who works as <em>Futurist</em> (what an awesome job title). More to come soon, it’s scheduled for mid-next year. Beside that, I wrote a plain JavaScript <a href="https://github.com/ThibaultJanBeyer/dragNdrop/">drag and drop plugin </a>since I could not find any good one that 1. is compatible with legacy browsers as IE8, 2. is lightweight and simple to understand, 3. Is flexible, 4. Is not jquery dependant.<br />
Lastly, to dive deeper in the React library, I’m working on a small Christmas/New-Year project now involving some webGL.</p>
<p><img class="aligncenter size-medium wp-image-2899" src="/assets/IMG_20161215_123147-400x300.jpg" alt="a pile of books" width="400" height="300" /></p>
<p>During all that time, I continued to read a lot interesting books:</p>
<p>I’ve read “<a href="https://www.amazon.de/gp/product/0321965515/ref=as_li_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=0321965515&linkCode=as2&tag=httpthibaulco-21">Don’t make me think</a>”. It’s quite a nice book on usability. Steve Krug starts with some basic info on how a user interacts with a website, what he looks at, how important the sites structure, clear buttons, a breadcrumb navigation is. He ends with a huge chapter on user testings and how to easily conduct them.</p>
<p>“<a href="https://www.amazon.de/gp/product/0007427921/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=0007427921&linkCode=as2&tag=httpthibaulco-21">Knowledge is Beautiful</a>”, is a very interesting book by David McCandless, showcasing all sort of information with a focus on data-visualization. A great source of inspiration.</p>
<p><a href="https://www.amazon.de/gp/product/3874398293/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=3874398293&linkCode=as2&tag=httpthibaulco-21">“Die Kunst ein kreatives Leben zu führen</a>” and “<a href="https://www.amazon.de/gp/product/3874397866/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=3874397866&linkCode=as2&tag=httpthibaulco-21">Kreativität Aushalten</a>”, both by Frank Berzbach, both very philosophical books on how to prevent burnout through simple everyday meditation plus how to build and keep a good work ethic and work-life balance. They kinda influenced me to do dorodangos and write the <a href="http://blog.thibaultjanbeyer.com/portfolio/how-to-dorodango/">dorodango tutorial</a>. I don’t know if this one was translated in English tho’.<br />
<img class="alignright size-medium wp-image-2900" src="/assets/erste_hilfe_in_typografie5-400x200.jpg" alt="erste hilfe typographie buch / book" width="400" height="200" /></p>
<p>“<a href="https://www.amazon.de/gp/product/3874394743/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=3874394743&linkCode=as2&tag=httpthibaulco-21">Erste Hilfe Typographie</a>” by Hans Peter Willberg and Friedrich Forssmann, probably one of the most comprehensive books on typography I’ve read so far. Although not talking much about webdesign, it still heavily inspired me to write the <a href="http://blog.thibaultjanbeyer.com/portfolio/quick-guide-to-web-typography/">guide to web-typography</a>.</p>
<p>“<a href="https://www.amazon.de/gp/product/3499612526/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=3499612526&linkCode=as2&tag=httpthibaulco-21">Crashkurs in Typo und Layout</a>” by Cyrus Dominik Khazaeli was a recommendation from our typography teacher and has over 400 pages. Nonetheless, I can’t recommend it. All those pages could be summarized in probably 10. The only good thing is that it is filled with comprehensible examples and screen-shots.</p>
<p>“<a href="https://www.amazon.de/gp/product/1781571465/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=1781571465&linkCode=as2&tag=httpthibaulco-21">What They Didn't Teach You in Design School</a>” I attended a talk from Phil Cleaver which motivated me to buy the book. While the speech was great, the book is not. It’s nothing new and nothing helpful for me. What Phil Cleaver tries to say is that everything you do has to be design and that you have to see yourself as a brand: start creating your brand identity, brand design and promoting/selling it and that you will be judged for everything you do, even the tiniest little piece you produce. That was pretty obvious and no news to me.</p>
<p>“<a href="https://www.amazon.de/gp/product/1439199191/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=1439199191&linkCode=as2&tag=httpthibaulco-21">How to win friends and influence people</a>” by Dale Carnegie. This book with the very cheesy title is in fact very old (first published 1937) but still the best book on inter-human relations I’ve read. There is a new version: “<a href="https://www.amazon.de/gp/product/1451612591/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=1451612591&linkCode=as2&tag=httpthibaulco-21">How to win friends and influence people in the digital age</a>” not written by Dale Carnegie himself but by members of the Carnegie foundation that I can not recommend. Compared to the original it was very boring. I really missed Dales great sense of humor.</p>
<p>“<a href="https://www.amazon.de/gp/product/2212140231/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=2212140231&linkCode=as2&tag=httpthibaulco-21">CSS3 : Pratique du design web</a>” a book written by Raphaël Goetter and Hugo Giraudel. I worked with Hugo at edenspeakermann_. He’s a very friendly, intelligent and inspiring guy. The book aims for devs having already some knowledge of CSS and want to dive deeper. It showcases CSS attributes, hacks and techniques with examples and the corresponding browser-support matrix. I clearly recommend that one. Don’t know about the translation tho’.</p>
<p>Lastly, I also started teaching myself Japanese. To achieve that, I have a new morning routine: 10 minutes of Japanese every day. I use “<a href="https://www.amazon.de/gp/product/0976998122/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=0976998122&linkCode=as2&tag=httpthibaulco-21">Japanese from Zero</a>” by George Trombley and Yukari Takenaka, which is a very good book for self-education. To support these studies I regularly use <a href="https://www.memrise.com/">Memrize</a>. Memrize is basically an online card learning tool with audio snipets and a good gamification. However, <em>watashi no nihongo wa yoku arimasen</em>, meaning, my Japanese is not good. Self learning is on the one hand fun because it costs nothing and is easy to add to your daily routine (btw. quicktip: creating a routine is the most important thing to do if you want to learn something by yourself) but on the other hand it has the big disadvantage that you’ll take way longer than in a guided course. I’m quite good at reading and writing (only hiragana tho’) but I obviously lack speaking and understanding skills. So I’ll probably start a course next year.<br />
Why? In average a human is capable of speaking 6 languages fluently. I already know 3, I would love to fill up all 6 before dying.</p>
<p> </p>
<p>That was the quick update. Thanks for being loyal. What do you think of the dragNdrop plugin? What’s your opinion on those books? What was your favourite/most inspiring read/talk/event this year? Was your year as filled as mine? What happened?</p>
<p>Read you soon, –TJB</p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer; top: 3263px; left: 429px;">Save</span></p>Hello dear reader, this year happened so much, that I did not find…How to make a dorodango2016-06-22T00:00:00+00:002016-06-22T00:00:00+00:00https://blog.thibaultjanbeyer.com/how-to-dorodango<p>After my last more technical tutorial, the <a href="http://blog.thibaultjanbeyer.com/portfolio/quick-guide-to-web-typography/">typography guide</a> you might want something more relaxing. So, just for fun, I tried the art of dorodango, it’s extremely meditative, maybe it’s something you’ll appreciate doing to counteract your intense business life and enhance your well-being. It costs nothing and is easy to do, give it a shot.</p>
<h2>What is dorodango?</h2>
<p>So I stumbled upon this awesome video from <a href="https://vimeo.com/p2photo">P2 Photography</a> on <a href="http://www.dorodango.com/about.html">Bruce Gardner</a>, who is a <a href="https://en.wikipedia.org/wiki/Dorodango">dorodango</a> artist. Dorodango is a Japanese art form in which earth and water are molded to create a delicate shiny sphere, resembling a billiard ball. Here is <a href="https://vimeo.com/130927316">the video</a>:</p>
<p>[embed]https://vimeo.com/130927316[/embed]</p>
<p>Which inspired me to try it myself. That being explained, welcome to my tutorial on Dorodango:</p>
<h2>How to make a Dorodango</h2>
<h3>What you need</h3>
<ul>
<li>Two clean container</li>
<li>A fine-meshed sieve</li>
<li>Water & Dirt</li>
<li>A Pillow</li>
<li>3x Plastic Bag</li>
</ul>
<p>As you can see these are materials everyone is able to get without large spending. Worst case the total cost will be ~10$. But it is very time-consuming, so what you’ll need is time. But trust me, it is very relaxing, even somewhat meditative.</p>
<h3>Form a ball</h3>
<p>First filter your dirt with your fine meshed sieve so that you get rid of rocks and twigs.</p>
<p><img class="aligncenter size-full wp-image-2539" src="/assets/filter-dirt.gif" alt="shaking the sieve to filter the dirt" width="500" height="282" /></p>
<p> </p>
<p>Then grab some of it (different dirt will create different colors and different textures, so every ball will differ) and put it in another clean container. Mix it together with a little water until you create mud that feels like dough.</p>
<p><img class="aligncenter size-full wp-image-2534" src="/assets/shape-ball-1.gif" alt="adding water to the bowl filled with some dirt, then shaping the dirt into a ball" width="500" height="281" /></p>
<p>Lastly, begin to shape that wet mud to a sphere try to gently squeeze out the water while shaping it. You need a smooth, round core to begin your dorodango, any cracks can ruin it.</p>
<p>Do that until your sphere becomes sticky like cake dough, if needed, add more dirt to absorb the moisture.</p>
<p><img class="aligncenter size-full wp-image-2533" src="/assets/shaping-ball-further-1.gif" alt="further shape the ball by sprinkeling dust on it" width="500" height="281" /></p>
<h3>The layers</h3>
<p>Take some of your fine dirt and sprinkle it over your ball. While doing so, continue to shape your sphere. Roll your ball with one hand and shape it with the other. Only press lightly, you don’t want to remove a layer of dirt. Do this until the surface is dry. If the surface begins to crack, you can add a bit of water to the surface to help smooth it back out.</p>
<p><img class="aligncenter size-full wp-image-2535" src="/assets/plastic-bag-1.gif" alt="placing the ball in a plastic bag" width="500" height="281" /></p>
<p>Once dry, put your ball in a plastic bag. Lay it on your pillow to keep its ball shape. Leave it there enough time for moisture to condense on the surface of the sphere and the bag. It will take one or two hours. When the outer layer is humid again, remove the ball from the bag and repeat: take some fine dirt and sprinkle it over your ball while shaping it into a sphere. Then place it in the bag again. Do this about ten times. Every time you repeat this it will take longer for your ball to become humid again. So put it in the fridge if you’re not that patient, it will go faster, but be careful not to over chill. 30-60 minutes in the fridge are enough. Don’t forget the pillow.</p>
<h3>Dust it</h3>
<p>For this step, you need extremely fine and dry dirt. Keep sifting your dirt to create finer dirt until it feels like dust. Pat your dirt to get a fine layer of dust on your hand. Apply this dust all over your sphere’s surface. Remove excess dirt. Do this until the surface feels dry and dusty. Place it in a new plastic bag and leave it in the fridge overnight. Repeat this process until dust no longer sticks to the surface. Then place your dorodango in a new bag again for one last sweat.</p>
<p><img class="aligncenter size-full wp-image-2540" src="/assets/polishing-1.gif" alt="polish the ball with a cloth" width="500" height="281" /></p>
<h3>Polish it</h3>
<p>Then begin polishing it with a cloth until it starts to shine! This might take very long, but at the end you should have something like this:</p>
<p><img class="aligncenter wp-image-2538 size-medium" src="/assets/dorodango-e1466504007748-400x309.jpg" alt="a beautiful polished shiny ball of mud called dorodango" width="400" height="309" /></p>
<p>It took me several trials until I finally succeeded. Welcome to the Zen part of life :)</p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 0.85; z-index: 8675309; display: none; cursor: pointer; top: 3616px; left: 150px;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 1; z-index: 8675309; display: none; cursor: pointer;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 0.85; z-index: 8675309; display: none; cursor: pointer; top: 1878px; left: 150px;">Save</span></p>
<p><span style="border-radius: 2px; text-indent: 20px; width: auto; padding: 0px 4px 0px 0px; text-align: center; font: bold 11px/20px 'Helvetica Neue',Helvetica,sans-serif; color: #ffffff; background: #bd081c no-repeat scroll 3px 50% / 14px 14px; position: absolute; opacity: 0.85; z-index: 8675309; display: none; cursor: pointer; top: 3616px; left: 131px;">Save</span></p>After my last more technical tutorial, the typography guide you might want something…Quick Guide to web typography2016-05-18T00:00:00+00:002016-05-18T00:00:00+00:00https://blog.thibaultjanbeyer.com/quick-guide-to-web-typography<h6>Typography is probably the most overlooked thing when developing for the web. However, if you want a decent design, it’s the most important one.</h6>
<div class="blog-adv--right">
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7411822855484586" data-ad-slot="1399062816" data-ad-format="auto"></ins>
</div>
<p>When type is bad your product is likely to look unprofessional. The aim of this post is to handhold beginners in creating impactful typography for their websites. I’m writing for programmers/developers who want to know the secret of beautiful websites. I’m pretty sure that you have a lot of textual content that you want to display in a way that people enjoy reading it. So let’s start.</p>
<p>Since typography has a tradition that goes back to the first days of human kind you’ll find a lot of literature on that matter. Most principles also come true for digital design. So, let me give you some general typographical knowledge first.</p>
<p> </p>
<p> </p>
<p><img class="aligncenter size-full wp-image-2452" src="/assets/choose-font.gif" alt="animated image: choosing the right font" width="500" height="180" /></p>
<h2>Choosing the right font</h2>
<p>There is not such thing as a universal right font. Whether a font is good or not depends on many factors such as your audience, language, the message/feeling you want to convey and personal taste. Every typeface is unique and thus has a unique look and feel. Some appear friendly, other serious, other artsy or even intimidating. That makes the process of choosing the right one difficult. No wonder that people commit their whole life on the subject. <i class="hilite">This might be why people just go for the most popular or the standard. Let’s change that!</i> If you don’t want to write a thesis on typography it is easier than you might expect. Choosing the right font really comes down to the following points.</p>
<h3>1. Choose one that is readable</h3>
<p>This should be granted. When you’re still able to read your text while being drunk under bad light condition, you can use it. But still, some unreadable typefaces can be interesting. So you’re allowed to break the readability rule if you want to add some visual tension to your design. If you do so, use it wisely. Only for big headlines where it is not important that the user reads them carefully.</p>
<h3>2. Choose one that fits the content</h3>
<p>Do you want something that provokes intense feelings or that is easy for the eye? Test the typeface on the device where it will be read. Some work better on some devices than other. Garamond is considered to be the most readable font for printed books while Open Sans enjoys a good reputation on screens. When building a website/app for children and reading beginners, choose a font where you can clearly differentiate characters. E.g. I and l, but also d should not just be a mirrored b but have a different look.<br />
Avoid: Arial, Times New Roman, Comic Sans, Trajan, Papyrus. Some of them are ugly by nature, other just overused. Only use them when you know what you’re doing.</p>
<h3>3. Choose one that conveys the right message</h3>
<p><i class="hilite">Different families evoke different feelings.</i> <a href="https://www.smashingmagazine.com/2010/12/what-font-should-i-use-five-principles-for-choosing-and-using-typefaces/" target="_blank">Dan Mayer did a good job</a> at categorizing the common families into five groups:</p>
<p><img class="wp-image-2454 alignnone" src="/assets/geometric-sans-400x96.png" alt="geometric sans futura" width="319" height="70" /><strong><em><br />
Geometric Sans </em> </strong>based on strict geometric forms, often referred as being minimalistic. They are clear, objective, modern, universal but also cold, impersonal, boring. Examples: Raleway, Helvetica, Univers, Futura, Avant Garde, Akzidenz Grotesk, Franklin Gothic, Gotham.</p>
<p><img class="wp-image-2456 alignnone" src="/assets/humanist-sans-lato-400x80.png" alt="humanist sans lato" width="352" height="60" /><em><strong><br />
Humanist Sans</strong> </em> less strict than the Geometric, closer to handwriting and thus friendlier. They are modern yet human, clear yet emphatic but can also look fake, uncertain, generic. Examples: Lato, Open Sans, Roboto, Gill Sans, Frutiger, Myriad, Optima, Verdana.</p>
<p><img class="wp-image-2457 alignnone" src="/assets/old-style-garamond-400x163.png" alt="old style garamond" width="181" height="59" /><em><strong><br />
Old Style</strong></em> waking up the past. They feel classic, traditional which can be good and bad at the same time. It depends if you want it to feel traditional or not. Examples: Garamond, Garamond, Garamond and Jenson, Bembo, Palatino.</p>
<p><img class="wp-image-2458 alignnone" src="/assets/transitional-modern-baskerville-bodoni-400x72.png" alt="transitional modern baskerville bodoni" width="420" height="59" /><em><strong><br />
Transitional and Modern</strong></em> more geometric, sharp and versatile than the old style. Higher contrast in thick and thin strokes. Strong, stylish, dynamic but can also look strange. Examples: Baskerville, Bodoni, Didot.</p>
<p><img class="wp-image-2459 alignnone" src="/assets/slab-serif-courier-400x65.png" alt="slab serif courier" width="353" height="48" /><strong><em><br />
Slab Serifs</em> </strong> have very specific associations (thinker, tough guy, bully, nerd, urban, sophisticated, cowboy). They add character to your design but can easily become too much distraction. Examples: ChunkFive, Roboto Slab, Clarendon, Rockwell, Courier, Lubalin Graph, Archer.</p>
<h3>Rag?</h3>
<p><img class="wp-image-2462 alignright" src="/assets/compare-similar-fonts-with-rag-1-400x103.png" alt="compare similar fonts with rag" width="298" height="60" /> The best way to compare similar fonts is by comparing the word Rag, the biggest difference is often found in those three letters.</p>
<h3>Round ?</h3>
<p><img class="wp-image-2463 alignright" src="/assets/Visualcommunication-athens-airport-copy.jpg" alt="Flights panel using rounded typo" width="259" height="80" />The rounded versions are more readable in sunlight/light reflections. As for highway signs, or for light-boxes. Rounded corners reduce the light irradiation to better distinguish an <em>e</em> from an <em>a</em> for example. Round edge = less area = less light blur. Since any electronic device emits light, in theory, the rounded versions should be more readable. Although the impact is very subtle.<strong><br />
</strong></p>
<p> </p>
<p> </p>
<p><img class="aligncenter size-full wp-image-2478" src="/assets/combine-font-1.gif" alt="font combinations" width="500" height="179" /></p>
<h2>Combining</h2>
<p>Of course one font is enough if you use different weights. If you limit yourself to one font and do it well, your designs can look clear and minimalist. It is how you’ll get what is called the <a href="https://en.wikipedia.org/wiki/Scandinavian_design" target="_blank">Scandinavian design</a>. However, having two font-families can create a huge impact. What web-designers often do is to choose a different Family for their headings. What works best is a Serif font as header and a sans-serif for the paragraphs or vice-versa. Simply because it is the strongest layer of contrast you can add. Hence, the masters of traditional typography: <a href="https://en.wikipedia.org/wiki/Emil_Ruder" target="_blank">Emil Ruder</a>, <a href="https://en.wikipedia.org/wiki/Anton_Stankowski" target="_blank">Anton Stankowsky</a> and <a href="https://en.wikipedia.org/wiki/Otl_Aicher" target="_blank">Otl Aicher</a>, to name a few, teach us to use sans-serif for headings and serif for copy. It is a good practice. But if your audience do not have top notch retina displays, a sans-serif for the copy and serifs for headings is better since bad displays have issues displaying serifs well.<br />
Always go for high contrast:</p>
<p><a href="/assets/high-contrast-typography.png"><img class="alignnone wp-image-2481 size-full" src="/assets/high-contrast-typography.png" alt="high-contrast-typography" width="1464" height="362" /></a></p>
<p>The example on the right is much more pleasant, isn’t it? The reason is that the seconds contrast is higher: it’s a bold vs thin weight, it’s a (transitional) serif font vs a (humanist) sans, an old font with tradition (Bodoni) vs a very new and modern font (Fira Sans). While keeping the same text flow: have a close look at the typefaces, in both you can clearly see a similar kind of duck board. Also, when you look at the <a href="http://www.typographydeconstructed.com/cap-height/" target="_blank">cap-height</a>, both have smaller t letters and the point of their i is also very high. <i class="hilite">Both examples convey that the author/website/text is cultured due to use of a traditional font</i> (sometimes using a serif is enough to evoke that feeling). However, the second example counteracts this feeling by using a very modern copy font and thus communicate that while being intellectual he isn’t stuck in ancient history. It gives an extra modern touch.</p>
<p>What if you don’t have a large collection of fonts and only little knowledge? Looking at suggestions from professionals is always a good idea; They all have great suggestions, <a href="https://de.wikipedia.org/wiki/Hans_Peter_Willberg" target="_blank">Hans Peter Willberg</a> & <a href="https://de.wikipedia.org/wiki/Friedrich_Forssman" target="_blank">Friedrich Frossman</a> for example suggest to combine Garamond + Gill, Helvetica + Walbaum or even Futura + Bodoni but never an old style with a transitional. It is also a good practice to look at what other professionals currently do. <a href="http://typ.io/?kind=popular&library=&tag=&font=" target="_blank">Typ.io</a> is a very good web-app that will save your time doing so. You’ll find a decent amount of other web-apps out there. As a simple web-search could be frustrating, here is a small collection of good ones:</p>
<ul>
<li><a href="http://typ.io/?kind=popular&library=&tag=&font=" target="_blank">Typ.io</a>, as mentioned above</li>
<li><a href="http://femmebot.github.io/google-type/" target="_blank">Google-Type</a> & <a href="http://hellohappy.org/beautiful-web-type/" target="_blank">BeautifulWebType</a>, curated and well designed websites, pairing fonts from the google fonts library.</li>
<li><a href="http://typespiration.com/" target="_blank">Typespiration</a>, lots of great inspiration, also curated by designers. With css code.</li>
<li><a href="http://fontflame.com/" target="_blank">FontFlame</a>, a tinder approach to font pairing (it is not perfect but the more users it has the better it gets)</li>
<li><a href="http://www.typegenius.com/" target="_blank">Typegenius</a>, is quite good if you have a starting font. Downside: there are not so many at the moment.</li>
<li><a href="https://www.typewolf.com/" target="_blank">Typewolf</a>, curated collection of websites with good font pairings.</li>
<li><a href="http://justmytype.co/" target="_blank">JustMyType</a>, curated pairings from Typekit and Hoefler & co (if you are using any of these services)</li>
</ul>
<p> </p>
<p> </p>
<p><img class="aligncenter size-full wp-image-2487" src="/assets/adjust-font-1.gif" alt="adjust font typography" width="500" height="180" /></p>
<h2>Adjusting</h2>
<p>Once you have the right fonts for your job, the most difficult part is done. Make sure to use a webfont. It has more information than the regular one. E.g. a web specific kerning. Nowadays almost every professional Font website offers web versions. Fonts from the major <a href="http://www.webopedia.com/TERM/C/CDN.html" target="_blank">CDNs</a> as <a href="https://typekit.com/" target="_blank">Typekit</a>, <a href="http://www.typography.com/cloud/welcome/" target="_blank">Hoefler&Co.</a>, <a href="http://www.fonts.com/web-fonts" target="_blank">Fonts.com</a>, <a href="https://edgewebfonts.adobe.com/index" target="_blank">EdgeWebfonts</a> and <a href="https://www.google.com/fonts" target="_blank">google fonts</a> are webfonts. Another good resource of free webfonts is the <a href="https://www.theleagueofmoveabletype.com/" target="_blank">league of movable type</a>. Today, all webfonts should be distributed with following filetypes: .woff, .woff2, .eot, .ttf and .svg. There are services to <a href="https://onlinefontconverter.com/" target="_blank">convert your font</a> but results will differ from case to case, so make sure to test them. Now you can start implementing them. But there are some things to pay attention on, and this is where digital differs from print.</p>
<h3>Font Size</h3>
<p>people always refer to 12px/pt for being the most readable <a href="https://css-tricks.com/almanac/properties/f/font-size/" target="_blank">font-size</a>. That’s true for print but not for web. 1em is the browsers default, <a href="https://developer.mozilla.org/en/docs/Web/CSS/font-size#Ems">which is most probably 16px</a>, that’s OK. But, even better is having <i class="hilite">16–18px on small screens and 18–21px on wide screens</i>. That might sound confusing but keep in mind, that the distance of a mobile device to your eyes is less than the usual distance to desktops or laptops. Go for large headings: 35–50 for h1 and 28–40 on h2. Don’t go smaller than 10px. Unimportant notes should be around 12–15px. This article itself is set in 2rem = 20px. Dare to increase your font size, your readers will be thankful.</p>
<p><em><strong>The power of <a href="http://webdesign.tutsplus.com/tutorials/comprehensive-guide-when-to-use-em-vs-rem--cms-23984" target="_blank">rem</a> units </strong></em> Rem gives you flexibility. Scaling elements up and down becomes a breeze. It will make your designs easier to adjust during development and allow users to control the scale of your sites for better accessibility. Em is good but becomes very complex since em is always dependent on it’s parent element. That’s why rem (root em) was introduced. It is only dependent on the root of your document (the html tag). E.g. in general browsers have the standard value of 16px, then for a div with 2em the content would have 32px. Now let’s say I add another div as child of the first one with also 2em, the content of that one will have 64px = 32*2. Confusing right? If rem is used instead the first and second div would both have 32px since rem always take the root element (html) as base, not the parent element. For even more ease of use you can set your html font-size to 62.5% = 10px, then 1.7rem is equal to 17px. If for some reason you want to increase or decrease your overall font-size, it only comes down to adjusting the font-size of your html element. All other elements will adapt. Cool! Having smaller font-sizes on mobiles is now very easy to do.</p>
<h3>Spacing</h3>
<p><a href="/assets/letter-spacing.png"><img class="alignright wp-image-2479 size-medium" src="/assets/letter-spacing-400x70.png" alt="letter-spacing -0.005rem" width="400" height="70" /></a> <em><strong>Letter Spacing</strong></em> The problem with decreasing or increasing the letter-spacing is that <i class="hilite">it might break the fonts ligature</i>. So, always check if your ligatures are still all right when changing the letter-spacing. The magic number of letter-spacing: -0.05px; has been around for a while. If you look at the comparison, the kerning seems better with a -.005rem spacing. The <em>s</em>, for example, is almost touching the <em>t</em> without that letter spacing. Overall, your text blocks will look more solid with -.005rem. An extra of +0.1-+0.4px letter-spacing might be a good idea if you feel that your letters are to close to each other or not that readable. Also, for small text, for all caps or light text on dark background use a wider letter-spacing.<br />
<a href="/assets/letter-spacing-2.png"><img class="alignright wp-image-2480 size-medium" src="/assets/letter-spacing-2-400x82.png" alt="big headlines, reduced letter spacing" width="400" height="82" /></a> <a href="http://www.btk-fh.de/de/team/cyrus-khazaeli/" target="_blank">Prof. Cyrus Dominik Khazaeli</a> suggests to decrease the spacing the larger the font-size gets to increase its impact. See how the difference in spacing is changing the tone of the typeface? The headline with reduced spacing feels way more resolute and expressive.</p>
<p><em><strong>Word Spacing</strong></em> The word-spacing should always be smaller than your line-height. In general the default <a href="https://css-tricks.com/almanac/properties/w/word-spacing/" target="_blank">word-spacing</a> is fine.</p>
<p><a href="/assets/line-height.png"><img class="alignright wp-image-2483 size-medium" src="/assets/line-height-400x133.png" alt="line-height normal vs 1.6" width="400" height="133" /></a><em><strong>Line Height</strong></em> The longer your paragraph get the higher your line-height must be. Else the reader will get lost. In most cases, you’ll have a readability benefit by increasing the <a href="https://css-tricks.com/almanac/properties/l/line-height/" target="_blank">line-height</a> by around 1.2-1.6 depending on the font.</p>
<p><em><strong>Line Width</strong></em> Lines that are too short or too long are tiring for your eyes, <i class="hilite">have lines with around 40–70 characters</i>. To achieve this on pages with a lot of text you can use <a href="https://css-tricks.com/almanac/properties/c/columns/">css columns</a> or fill in images or citations.</p>
<p><em><strong>Padding</strong></em> When you have text surrounded by borders or other elements, don’t forget to add some padding to your text blocks, otherwise they look squeezed. If possible have the distance to the top be slightly smaller than to the bottom, otherwise the text fall down optically (javierbytes <a href="http://javier.xyz/visual-center/?utm_content=buffer834e1&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer">visual center app</a> might be helpful to find the visual center of images)</p>
<p><em><strong><img class="alignright wp-image-2489" src="/assets/closer-headings-1.png" alt="headings closer to content" width="261" height="168" />Headings</strong></em> Headings should always be closer to the elements or paragraphs they belong to. Default heading settings make them float between two paragraphs with equal distance to each. Change that to be closer to the related paragraph and further away from the other one. That will help your readers brain to draw optical connections. Actually that is true for all content relations (e.g. graphics).</p>
<p><em><strong>Spacing</strong></em> Instead of using weird borders to separate and structure your content, play around with the spacing of your elements. Often <i class="hilite">adding space resolves your structuring issue</i>. Try to use borders only if absolutely necessary, often they are more disruptive than helpful. Don’t be hesitant on white space, you have endless space available (pun not intended).</p>
<h3>Justification</h3>
<p>Avoid justification. The controls for nice justifications as we have them in traditional media is not given in css yet. The current results look poor, we have to wait until decent justifications are possible. I can’t recommend using a plugin for that matter, but it’s your best bet if you die for justified text. <a href="https://github.com/bramstein/typeset/" target="_blank">Typeset</a> e.g. is one. It is very important that the space between your words is not too small nor too larger. Hyphenation should be enabled and if possible controlled, so that you have breaks that make sense and try to avoid more than two breaks in one paragraph. CSS has a <a href="https://css-tricks.com/almanac/properties/h/hyphenate/" target="_blank">Hyphens</a> but the browser support is very bad. In HTML, you can use <i class="hilite">&shy;</i> to insert a soft hyphen where you want it to potentially break. You might also use a plugin to get nice hyphens as <a href="https://github.com/mnater/hyphenator" target="_blank">Hyphenator</a> or <a href="https://github.com/bramstein/hypher/" target="_blank">Hypher</a>. Never justify a heading. Never justify notes.</p>
<h3>Emphasis</h3>
<p><em><strong>Bolds</strong></em> Bold (font-weight: >600) is active. Shows what the text is about before starting to read.</p>
<p><em><strong>Coloring</strong></em> Colors are active and as strong as bolds. Unless you dim the color. So keep in mind, that your links drag attention (you can use <a href="http://codepen.io/ThibaultJanBeyer/pen/vGprqE">Metalinks</a>, to reduce it). Besides <a href="http://oregonstate.edu/accessibility/web" target="_blank">web-accessibility</a>, that’s one of the top reasons why you should always use <a href="https://www.nngroup.com/articles/writing-links/" target="_blank">descriptive links</a>. Stop linking the keyword <em>here</em>!</p>
<p><strong><em>Small Caps</em></strong> Small Caps (font-feature-settings: "smcp" 1; or font-variant: small-caps;): usually used for proper names. Add some letter-spacing if you use them. Only use them if your font supports them.</p>
<p><em><strong>All Caps</strong></em> All caps (text-transform: uppercase): shouting. Decrease the font size and add letter-spacing.</p>
<p><em><strong><a href="http://codepen.io/ThibaultJanBeyer/pen/LNeNrv"><img class="alignright wp-image-2484" src="/assets/underline-400x73.png" alt="smart underline" width="339" height="59" /></a>Underline</strong></em> Underline (text-decoration: underline): strong but less than bold/semi-bold text. Could be confused with links. Can be beautiful if well done but that is also impossible in proper css at the time being. There is <a href="https://wentin.github.io/underlineJS/" target="_blank">UnderlineJS</a> and <a href="https://eager.io/blog/smarter-link-underlines/" target="_blank">Eager’s solution</a> although those are bulky. If you’re dying for underlines as I am, use <a href="http://codepen.io/ThibaultJanBeyer/pen/LNeNrv" target="_blank">this small hack</a> inspired by Eager’s solution, it fakes it quite well with a decent support. It’s called <a href="http://codepen.io/ThibaultJanBeyer/pen/LNeNrv" target="_blank">SmartUnderlines</a>. Anyway, a good underline is as thick as a normal character line, it has holes around the descender and should be at the <a href="https://en.wikipedia.org/wiki/Golden_ratio" target="_blank">golden ratio</a> Y distance.</p>
<p><em><strong>Italic</strong></em> Italic is the softest emphasis. It is only visible when reading the text. Make sure to only use italics if the font supports it (else it only weirdly stretches the characters).</p>
<h3>Hierarchy</h3>
<p>Make sure to have a good structure in your writings, you don’t want your reader to get lost. This is especially important for long writings. The book <a href="http://www.amazon.de/Erste-Hilfe-Typografie-Peter-Willberg/dp/3874394743">first aid in typography</a> from Hans Peter Willberg & Friedrich Frossman suggest following heading structure:</p>
<p><em><strong><a href="/assets/structure.png"><img class="alignright wp-image-2485 size-medium" src="/assets/structure-400x287.png" alt="Heading structure examples" width="400" height="287" /></a>1.</strong></em> A huge, bold h1 with a big margin. A bold h2 at smaller size but with the same margin. h3 in italic, same size as the copy, without bottom margin. Lastly h4 bold and italic within the paragraph.</p>
<p><strong><em>2.</em></strong> Huge, bold h1 with big margin. Bold h2 at smaller size but with same margin. h3 same size, weight and style as copy but still with the same margin as h1 and h2. Lastly h4 is italic without bottom margin</p>
<p>I use a variation of 1 in my writings. You obviously don’t need such a deep structure if you only have a small textual content. As long as you have a clear hierarchy you’re good. Beware that people are very likely to lose track if you go deeper than four levels. Even h4 is borderline. For smaller writings h1 and maybe h2 and your copy is enough.</p>
<h3>Smart Characters</h3>
<p><a href="http://smartquotesforsmartpeople.com/"><img class="alignright wp-image-2273" src="/assets/Screen-Shot-2016-04-05-at-16.15.42-400x138.png" alt="smart quotes" width="299" height="80" /></a> Use <a href="http://smartquotesforsmartpeople.com/" target="_blank">smart quotes</a>.<br />
Don’t forget other basic character rules as differentiating a hyphens from a dash; A hyphens binds two words together, a dash indicates distance (e.g. re-do vs 2000–2004), a dash indicates pauses and is used for the minus sign. Besides your school, <a href="http://www.nationalpunctuationday.com/" target="_blank">national punctuation day</a> is a good resource to learn more about smart characters.</p>
<h3>Specialities</h3>
<p><em><strong>Color</strong></em> Full black on full white is painful to read, you should use some lighter black such as #333 and darker white as #f6f6f6 for even better readability. Firefox will still have some rendering issues, to fix that use <i class="hilite">-moz-osx-font-smoothing: grayscale</i>. However, full white is OK if you have already soften your black. Note that shitty screens won’t make any difference.</p>
<p><img class="alignright wp-image-2276 " src="/assets/ligaturbeispiel1.thumb_.jpg.26177ecbdabf920f0942fde78c258bc8-400x130.jpg" alt="ligatures" width="231" height="82" /><em><strong>Ligatures</strong></em> If your font has ligatures or any other specialties, you can enable them with <a href="https://css-tricks.com/almanac/properties/f/font-feature-settings/" target="_blank">font-feature-settings</a> in css (it’s enabled by default on most browsers). Use the keyword liga for ligatures.</p>
<p><img class="wp-image-2274 alignright" src="/assets/800px-Kerning_EN.svg_-400x279.png" alt="Kerning" width="241" height="168" /></p>
<p><em><strong>Kerning</strong></em> Kerning is by default metric, you can enable optical kerning with <a href="https://css-tricks.com/almanac/properties/f/font-feature-settings/" target="_blank">font-feature-settings</a> and the Keyword kern. Together that would be: font-feature-settings: "liga" 1,"kern" 1;. kerning will also be enabled via text rendering options (see below). Following letters profit the most of proper kerning: A V W L T and f r v y.<br />
This <a href="https://css-tricks.com/almanac/properties/f/font-feature-settings/" target="_blank">font-feature-settings</a> is very powerful, you should check it out. Despite, there is one downside, font-feature-settings is sadly not widely supported yet and it is dependent on a font to supply that extra information (this is how you will distinguish the good web-fonts from the bad).</p>
<p><em><strong>Text Rendering</strong></em> The css property <a href="https://css-tricks.com/almanac/properties/t/text-rendering/">text-rendering</a> allows you to chose quality of text over speed and vice-versa. <i class="hilite">Use text-rendering: optimizeLegibility; for an extra readability boost</i>. Beware, there are some <a href="http://aestheticallyloyal.com/public/optimize-legibility/" target="_blank">bugs with text-rendering</a>, also negative impact on page load and overall performance when used too often. So, you might add it only on longer static text.</p>
<h2>Wrapping up</h2>
<p>Basically you should now be set to create awesome, usable and readable works. Always write comments if you feel that I forgot something or if you know anything better. Living documents are always more fun than static ones. Also I would enjoy to see some of your before after pictures if you feel like reworking your page. Have fun!</p>
<p>PS: don’t forget to share the knowledge and to follow me <a href="https://twitter.com/ThibaultBeyer">on twitter <i class="fab fa-twitter"></i></a> or via <a class="toggle-sidebar" data-a11y-dialog-show="subscribe-dialog" href="#site-sidebar" data-effect="push-effect-push2">email <i class="fa fa-fw fa-columns"></i></a> if you liked this post :)</p>Typography is probably the most overlooked thing when developing for the web. However,…Free origami font2016-05-06T00:00:00+00:002016-05-06T00:00:00+00:00https://blog.thibaultjanbeyer.com/free-origami-font<p>Hey everyone, due to the lack of time I will be very brief:</p>
<p>You are absolutely awesome! To celebrate that and 100 email subscribers I’m giving away my <a href="https://kit.thibaultjanbeyer.com/freebies/fonts/paperfold/Thibault-Jan-Beyer-Paperfont_RL.zip">origami font for free <i class="fa fa-download"></i></a> ! Make sure to hit <span class="toggle-sidebar site-bar-controls-tooltip" data-a11y-dialog-show="subscribe-dialog"><a href="#">subscribe <i class="fa fa-fw fa-columns"></i></a></span> if you haven’t yet. I made it 2013 for a <a href="http://blog.thibaultjanbeyer.com/portfolio/the-birds/">typographical poster</a>. Feel free to expand it and use it for whatever you like. Would love to see what crazy stuff come up with!</p>
<p><a href="https://kit.thibaultjanbeyer.com/freebies/fonts/paperfold/Thibault-Jan-Beyer-Paperfont_RL.zip"><img class="alignnone wp-image-2464 size-full" src="/assets/paperfold-type.png" alt="free paperfold typeface font" width="914" height="893" /></a></p>Here is a free origami stile font for y’all