<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Tutorialhell.dev blog]]></title><description><![CDATA[I explain underlying concepts that aren't usually covered in courses. When you understand a concept, you know where and how to apply it.]]></description><link>https://blog.tutorialhell.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 06 Oct 2026 03:46:39 GMT</lastBuildDate><atom:link href="https://blog.tutorialhell.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Must-Have Practical Tutorial on Node.js Modules for Badass Beginners]]></title><description><![CDATA[It's a practical tutorial that will provide you with everything you need to understand how require() works and how to use it efficiently. It includes detailed instructions and code examples that you can run either locally on your computer or in a pre...]]></description><link>https://blog.tutorialhell.dev/must-have-practical-tutorial-on-nodejs-modules-for-badass-beginners</link><guid isPermaLink="true">https://blog.tutorialhell.dev/must-have-practical-tutorial-on-nodejs-modules-for-badass-beginners</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Sandor]]></dc:creator><pubDate>Fri, 23 Feb 2024 10:10:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/L0oJ4Dlfyuo/upload/a62c167d807e4479349c676686d7c082.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708682947855/7d8520ce-5c65-403b-8f3d-e98478694f9a.png" alt class="image--center mx-auto" /></p>
<p>It's a practical tutorial that will provide you with everything you need to understand how <code>require()</code> works and how to use it efficiently. It includes detailed instructions and code examples that you can run either locally on your computer or in a prepared online Node environment to quickly get the hang of it. And there will be practical exercises waiting for you at the end of this tutorial.</p>
<p>It's part of my <a target="_blank" href="http://tutorialhell.dev">tutorialhell.dev</a> project, aimed at helping beginners learn easily without getting stuck.</p>
<p>In Node.js, a module is a self-contained block of code that doesn't affect other code. JavaScript files are treated as modules in Node.js, where you can export functions, objects, or values from one file and use them in another.</p>
<p>Node.js supports two module systems: CommonJS modules and ECMAScript modules.</p>
<ul>
<li><p>The <strong>CommonJS modules</strong> were the original method for packaging JavaScript code in Node.js.</p>
</li>
<li><p>The <strong>ECMAScript modules</strong> standard is utilized by browsers and other JavaScript runtimes and is generally viewed as the preferred approach for being future-proof. However, to get started, we will focus on CommonJS modules since they are still widely used. As we progress, I will introduce you to ECMAScript modules in the upcoming tutorials.</p>
</li>
</ul>
<p>Let's break down the basics, starting with how to create a module in Node.js, how to export from it, and how to use the exported entities in other files.</p>
<p>If you don't have Node.js set up, you can get started using a ready-made Node.js environment in this <a target="_blank" href="https://stackblitz.com/fork/github/stackblitz/starters/tree/main/nodemon?title=Nodemon%20Starter&amp;description=A%20simple%20starter%20for%20using%20nodemon%20printing%20no%20messages%20in%20a%20terminal">sandbox</a>.</p>
<h2 id="heading-creating-a-simple-module">Creating a Simple Module</h2>
<p><strong>Create a File</strong>: Every module is a JavaScript file. Create a file named 'myModule.js'.</p>
<p><strong>Write Some Code</strong>: Inside 'myModule.js', define a function that you want to make available outside this file.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
}
</code></pre>
<h2 id="heading-exporting-from-a-module">Exporting from a Module</h2>
<p>To make functions, objects, or values available outside the module where they are defined, you need to export them using <code>module.exports</code>.</p>
<p><code>module.exports</code> is an object included in every JavaScript file in Node.js by default. It is used to export functions, objects, or values from a module. Here is the full code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
}
<span class="hljs-built_in">module</span>.exports = sayHello;
</code></pre>
<h2 id="heading-importing-a-module">Importing a Module</h2>
<p>To use the exported entities from a module in another file, you need to require that module.</p>
<p><strong>Create Another File</strong>: 'index.js'. (It's already there if you are using the sandbox. Simply replace the contents with the code provided below.)</p>
<p><strong>Require the Module</strong>: Use the <code>require()</code> function to import the module, passing the path to the module file as an argument:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./myModule'</span>);
<span class="hljs-built_in">console</span>.log(sayHello(<span class="hljs-string">'World'</span>)); <span class="hljs-comment">// Outputs: Hello, World!</span>
</code></pre>
<p><strong>Explanation:</strong></p>
<p><code>require('./myModule')</code>: This line imports the module myModule.js. The <code>./</code> indicates that the file is located in the same directory as index.js. Node.js reads myModule.js, executes it, and then module.exports from myModule.js is returned by require() and assigned to the variable sayHello in index.js.</p>
<p><code>sayHello('World')</code>: This line calls the imported function with the argument 'World', and the function returns the string 'Hello, World!'.</p>
<h2 id="heading-multiple-exports">Multiple exports</h2>
<p>To perform multiple exports from a Node.js module, you can use either the <code>module.exports</code> object or the <code>exports</code> shorthand. Each approach allows you to export multiple items, such as functions, objects, or values, from a single module. Here's how you can do it:</p>
<ol>
<li>Using <code>module.exports</code></li>
</ol>
<p>You can directly assign an object to <code>module.exports</code> containing all the items you want to export. This approach is useful when you want to structure your exports clearly in one place. Create a 'multipleExport1.js' and paste the following code there:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Function 1'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func2</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Function 2'</span>);
}

<span class="hljs-built_in">module</span>.exports = {
  func1,
  func2,
};
</code></pre>
<ol>
<li>Using <code>exports</code></li>
</ol>
<p>The <code>exports</code> shorthand allows you to attach exports directly to the <code>exports</code> object. This is syntactically more concise for exporting multiple items. Create a 'multipleExport2.js' and paste the following code there:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">exports</span>.func3 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Function 3'</span>);
};

<span class="hljs-built_in">exports</span>.func4 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Function 4'</span>);
};
</code></pre>
<h2 id="heading-multiple-imports">Multiple imports</h2>
<p>Similarly, you would import these in another file like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport1'</span>);
<span class="hljs-keyword">const</span> myModule2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport2'</span>);
</code></pre>
<p>Or, using destructuring:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { func1, func2 } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport1'</span>);
<span class="hljs-keyword">const</span> { func3, func4 } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport2'</span>);
</code></pre>
<p>Replace the contents of the 'index.js' file with this code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./myModule'</span>);
<span class="hljs-built_in">console</span>.log(sayHello(<span class="hljs-string">'World'</span>)); <span class="hljs-comment">// Outputs: Hello, World!</span>

<span class="hljs-comment">// Approach 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'------- Approach 1 -------'</span>);
<span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport1'</span>);
<span class="hljs-keyword">const</span> myModule2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport2'</span>);

myModule.func1(); <span class="hljs-comment">// Calls 'Function 1'</span>
myModule.func2(); <span class="hljs-comment">// Calls 'Function 2'</span>

myModule2.func3(); <span class="hljs-comment">// Calls 'Function 3'</span>
myModule2.func4(); <span class="hljs-comment">// Calls 'Function 4'</span>

<span class="hljs-comment">// Approach 2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'------- Approach 2 -------'</span>);
<span class="hljs-keyword">const</span> { func1, func2 } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport1'</span>);
<span class="hljs-keyword">const</span> { func3, func4 } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport2'</span>);

func1(); <span class="hljs-comment">// Calls 'Function 1'</span>
func2(); <span class="hljs-comment">// Calls 'Function 2'</span>
func3(); <span class="hljs-comment">// Calls 'Function 3'</span>
func4(); <span class="hljs-comment">// Calls 'Function 4'</span>
</code></pre>
<p>And you should see the following logged in your terminal:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/133asmi2d05jvszdk3jf.png" alt="Node.js modules" /></p>
<p>You might have noticed that when functions are imported through destructuring, they are assigned unique identifiers like <code>func1</code>, <code>func2</code>, etc. This uniqueness is necessary because two functions with the same name cannot coexist in the same file (module). It requires us to use unique names in different modules, which is not convenient.</p>
<p>However, there is a technique to rename these functions while importing them. This allows functions to have identical names across multiple modules and be renamed when imported into the same file to avoid name collisions. Here is how you do it:</p>
<p>Create a new file named 'multipleExport3.js' and paste the following code there:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">exports</span>.func3 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Function 3 with an identical name from a different module'</span>);
};

<span class="hljs-built_in">exports</span>.func4 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Function 4 with an identical name from a different module'</span>);
};
</code></pre>
<p>Then add this code to the bottom of your 'index.js' file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {
  <span class="hljs-attr">func3</span>: renamedFunc3,
  <span class="hljs-attr">func4</span>: renamedFunc4,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./multipleExport3'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'------- Destructuring with Renaming -------'</span>);
renamedFunc3();
renamedFunc4();
</code></pre>
<p>And your updated terminal output will look like this:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pub4pnetn8bicsgu7usc.png" alt="Destructuring with Renaming" /></p>
<p>👉 Working code you can find <a target="_blank" href="https://stackblitz.com/edit/node-js-modules-www-tutorialhell-dev?file=index.js">here</a>.</p>
<h2 id="heading-choosing-between-moduleexports-and-exports">Choosing Between <code>module.exports</code> and <code>exports</code></h2>
<p>Use <code>module.exports</code> when you want to export a single item, like a function or an object, or when you prefer to define all exports at once in an object.</p>
<p>Use <code>exports</code> to attach multiple exports individually. This can be more straightforward when exporting several items but remember that you cannot assign directly to <code>exports</code> as it will break the reference to <code>module.exports</code>. For example, doing <code>exports = { func1, func2 }</code> will not work as expected.</p>
<p>Both methods are commonly used and choosing between them often comes down to preference and the specific needs of your module.</p>
<h2 id="heading-heres-a-breakdown-of-the-key-feature-that-every-beginner-should-grasp">Here’s a breakdown of the key feature that every beginner should grasp:</h2>
<h3 id="heading-require-is-synchronous-and-caches-modules"><code>require()</code> is Synchronous and Caches Modules</h3>
<p><strong>Synchronous Loading:</strong> When you use <code>require()</code> to import a module, Node.js reads and executes the entire module file synchronously. This means that Node.js will halt the execution of your code until the entire module is loaded. This behaviour is particularly important to understand because it affects how and where you use require() in your application. Here's a simple <a target="_blank" href="https://stackblitz.com/edit/synchronous-require-demo-nodejs?file=index.js">code example</a> to demonstrate that require() is synchronous in Node.js, meaning Node.js waits for the module to be fully loaded and executed before moving on to the next line of code.</p>
<p>Or try it out yourself by pasting the following code in the <a target="_blank" href="https://stackblitz.com/fork/github/stackblitz/starters/tree/main/nodemon?title=Nodemon%20Starter&amp;description=A%20simple%20starter%20for%20using%20nodemon%20printing%20no%20messages%20in%20a%20terminal">sandbox</a>.</p>
<p>Create a file named 'greet.js' and paste the following code there:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Loading greet.js...'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">'Hello and welcome to learning web development with www.tutorialhell.dev!'</span>
  );
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'greet.js loaded successfully.'</span>);

<span class="hljs-built_in">module</span>.exports = greet;
</code></pre>
<p>Create or update (it's already there in the sandbox) the 'index.js' file and paste the following code there:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Starting index.js...'</span>);

<span class="hljs-keyword">const</span> greet = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./greet'</span>); <span class="hljs-comment">// Synchronously loads and executes "greet.js"</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'greet.js has been required.'</span>);

greet();

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Ending index.js...'</span>);
</code></pre>
<p><strong>How it works:</strong> When you run 'index.js' using the command <code>node index.js</code>, you will see the logs in the following order, demonstrating the synchronous nature of <code>require()</code>:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06c8nw9uvqkpbhvsnhom.png" alt="Demonstrating the synchronous nature of require()" /></p>
<p>Notice how the execution of 'index.js' pauses until 'greet.js' is fully loaded and executed (evidenced by the logs from 'greet.js' appearing before the continuation of 'index.js').</p>
<blockquote>
<p>In simple terms, synchronous means doing things one by one in order, where you have to finish one thing before you can start the next thing.</p>
</blockquote>
<p><strong>Caching Mechanism</strong>: Node.js caches the first instance of each module you require. If you <code>require()</code> the same module multiple times in different parts of your application, <strong>Node.js will not reload or re-execute the module file</strong> after the first time it's loaded. Instead, <strong>it reuses the cached version</strong>. This caching mechanism improves performance by avoiding the overhead of loading and compiling the module's code multiple times. However, it also means that any state maintained in the module is shared across all parts of your application that import it.</p>
<blockquote>
<p>In simple terms, caching means storing something in a place where it can be quickly accessed later. It's like saving a shortcut to find information faster without having to go through the whole search process again.</p>
</blockquote>
<h2 id="heading-why-it-matters">Why It Matters</h2>
<p><strong>Performance Implications</strong>: Knowing that <code>require()</code> is synchronous helps in structuring your code for optimal performance, especially during the startup phase of an application. It encourages the practice of requiring modules at the beginning of files or in sections of the code where blocking the event loop has minimal impact on the application's responsiveness.</p>
<p>Understanding JavaScript's synchronous, single-threaded nature is key in Node.js to avoid blocking code. Node.js uses techniques like <strong>callbacks</strong>, <strong>promises</strong>, and <strong>async/await</strong> to enable asynchronous operations, preventing the event loop from being blocked. These methods allow Node.js applications to remain efficient and responsive, handling tasks in the background without slowing down the main execution flow.</p>
<p>Single-threaded means that a program or environment, like JavaScript in Node.js, can only execute one operation at a time on a single path of execution. Imagine it as a single-lane road where cars (operations) must go one after another, not side by side. This setup ensures that operations are carried out in sequence, but it also means that one operation must complete before the next one starts, preventing simultaneous execution of multiple operations.</p>
<p><strong>Module State Sharing</strong>: Awareness of the caching mechanism is important when designing modules. Since the same instance of a module is shared wherever it's required, any state stored in the module is also shared. This can be leveraged to maintain application-wide state but requires careful management to avoid unintended side effects.</p>
<p>In programming, "state" refers to the current condition or data held by an application or a module at any given time. It's like remembering the score while playing a game; just as the score tells you how well you're doing at that moment, the state in programming keeps track of information like what's been clicked, entered into forms, or saved temporarily as the program runs. This state can change based on what actions are taken within the application, just like the game score changes when you score points or lose points.</p>
<p>It's important to distinguish this concept of "state" from a database (DB). While a database can store data that might represent part of an application's state, such as user profiles or application settings, the "state" in the context of programming generally refers to the in-memory condition of an application at a specific moment. This includes data that the application is currently working with but hasn't necessarily saved to a database.</p>
<p><strong>Debugging</strong>: Understanding how <code>require()</code> works can aid in debugging issues related to module loading, such as why changes to a module don't seem to take effect (due to caching) or why an application may be blocking at startup (due to synchronous loading of modules).</p>
<h2 id="heading-practical-exercises">Practical Exercises</h2>
<p>To reinforce your understanding of the <code>require()</code> functionality and the caching mechanism, I recommend practising. Here is the Node.js <a target="_blank" href="https://stackblitz.com/fork/github/stackblitz/starters/tree/main/nodemon?title=Nodemon%20Starter&amp;description=A%20simple%20starter%20for%20using%20nodemon%20printing%20no%20messages%20in%20a%20terminal">sandbox</a>, in case you need it..</p>
<p><strong>Objective:</strong></p>
<p>Your task is to create a simple Node.js application that demonstrates how the state is shared and managed across modules due to Node.js's caching mechanism. You will create a shared state module and two additional modules that modify and display the shared state, respectively.</p>
<p><strong>Instructions:</strong></p>
<p><strong>1. Create the Shared State Module:</strong></p>
<ul>
<li><p>File Name: 'counterState.js'</p>
</li>
<li><p>Task: This module will maintain a counter. Write two functions within this module: one named <code>incrementCounter</code> to increment the counter and another named <code>getCounter</code> to retrieve the counter value. Export both functions.</p>
</li>
</ul>
<p>The counter code will look something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">incrementCounter</span>(<span class="hljs-params"></span>) </span>{
  count++;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> count;
}

<span class="hljs-built_in">module</span>.exports = { incrementCounter, getCounter };
</code></pre>
<p><strong>2. Create the First Additional Module:</strong></p>
<ul>
<li><p>File Name: 'incrementModule.js'</p>
</li>
<li><p>Task: This module will require 'counterState.js' and use its <code>incrementCounter</code> function to increment the counter, and the <code>getCounter</code> function to display the counter's current value. It should then log a message showing the new counter value. Export a function named <code>increment</code> that performs these tasks. You need to write this code yourself.</p>
</li>
</ul>
<p><strong>3. Create the Second Additional Module:</strong></p>
<ul>
<li><p>File Name: 'displayModule.js'</p>
</li>
<li><p>Task: This module will also require 'counterState.js' but will only use the <code>getCounter</code> function to display the current value of the counter. Export a function named <code>display</code> that logs the counter's current value. You need to write this code yourself.</p>
</li>
</ul>
<p><strong>4. Create the Entry Point File:</strong></p>
<ul>
<li><p>File Name: 'index.js'</p>
</li>
<li><p>Task: In this file, you will require both 'incrementModule.js' and 'displayModule.js'. Use their exported functions to increment the counter and display its value, demonstrating the shared state across modules. You need to write this code yourself.</p>
</li>
<li><p>Instructions: Increment the counter, display its value, and then increment it again to show the shared and persistent state. Then display the value again to see how it updates in the other file (module) that requires the 'counterState.js' module.</p>
</li>
</ul>
<p>The working code should log the following:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xpb7hvr43pe6x7j6zua9.png" alt="State Management Demo" /></p>
<p>By completing this homework, you will understand how Node.js caches imported modules, allowing shared state between different parts of your application. This knowledge is fundamental for efficient Node.js development, especially for applications relying on shared data across modules.</p>
<p><a target="_blank" href="https://stackblitz.com/edit/node-js-commonjs-modules-homework-solution?file=index.js">Here</a> are the solutions to the above practical exercises.</p>
<h2 id="heading-transferable-knowledge-and-patterns">Transferable Knowledge and Patterns</h2>
<ul>
<li><p><strong>Understanding of Synchronous Operations</strong>: Recognising that <code>require()</code> operates synchronously, halting execution until a module is fully loaded, <strong>teaches the general principle of synchronous execution in programming</strong>. This concept is critical for understanding how different parts of a program can affect execution flow and performance, applicable in various programming languages and environments.</p>
</li>
<li><p><strong>Importance of Caching for Performance</strong>: <strong>The caching mechanism of</strong> <code>require()</code> illustrates a fundamental performance optimisation technique used widely in computing. Caching, or temporarily storing data for quick access upon repeated requests, is a concept that can be applied in numerous scenarios beyond module loading, such as web content delivery, database queries, and more.</p>
</li>
<li><p><strong>Module State Sharing and Global State Management</strong>: The idea that a module's state is shared across all parts of an application that import it underscores the broader concept of global state management. This is a key consideration in software design, relevant for <strong>understanding how state is managed across an application</strong>.</p>
</li>
<li><p><strong>Performance Optimisation Practices</strong>: The advice to require modules at the beginning of files or in strategic code sections to minimise performance impact <strong>teaches a broader lesson on resource management and optimisation in software development</strong>. Prioritising resource-intensive operations and understanding their impact on the application's responsiveness and efficiency are valuable skills.</p>
</li>
<li><p><strong>Debugging and Troubleshooting</strong>: The emphasis on how understanding require()'s behaviour aids in debugging extends to a general principle in programming: <strong>knowing how your tools and frameworks work under the hood can significantly improve your ability to troubleshoot and solve problems</strong>. This is a critical skill for any developer, as it applies to debugging in all programming languages and environments.</p>
</li>
</ul>
<p>That said, understanding how to import modules in Node.js opens up a wealth of critical knowledge that you will learn once and use everywhere. It shows you how to avoid getting stuck.</p>
<p>You are more than welcome to explore these topics independently because it’s the best way to develop problem-solving skills. But keep in mind that we will gradually cover all these topics through my tutorials because that’s why <a target="_blank" href="http://tutorialhell.dev">tutorialhell.dev</a> was created.</p>
<h2 id="heading-learning-path-from-here">Learning path from here:</h2>
<p>The concepts mentioned in the examples, such as function definitions, template literals, and destructuring, are frequently used, and thus I strongly encourage you to engage in some self-learning as well. Yes, to develop problem-solving skills. I cannot emphasize this enough.</p>
<ul>
<li><p><strong>Introduction to Objects</strong>: Learn about JavaScript objects, including creation, access, methods, property shorthand and computed properties.</p>
</li>
<li><p><strong>Function Definitions</strong>: Explore different ways to define functions, including function declarations, function expressions, and arrow functions.</p>
</li>
<li><p><strong>Template Literals</strong>: Learn about string interpolation and multi-line strings in ES6, using backticks to define template literals and <code>${}</code> for embedding expressions.</p>
</li>
<li><p><strong>Destructuring</strong>: Understand the destructuring assignment syntax for arrays and objects.</p>
</li>
<li><p><strong>File Paths</strong>: Learn about relative and absolute file paths to grasp how to navigate and reference files within your projects effectively.</p>
</li>
</ul>
<hr />
<p>If you like this content, consider following me and subscribing to receive these cool tutorials as soon as they are ready.</p>
<p>The sunfish on the post cover was sourced from the O'Rly Generator.</p>
]]></content:encoded></item><item><title><![CDATA[You don't know Redis (Part 2)]]></title><description><![CDATA[In the first part of You don't know Redis, I built an app using Redis as a primary database. For most people, it might sound unusual simply because the key-value data structure seems suboptimal for handling complex data models.
In practice, the choic...]]></description><link>https://blog.tutorialhell.dev/you-dont-know-redis-part-2</link><guid isPermaLink="true">https://blog.tutorialhell.dev/you-dont-know-redis-part-2</guid><category><![CDATA[Redis]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Sandor]]></dc:creator><pubDate>Fri, 23 Jul 2021 13:23:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1626969175420/E_CxlDlBl.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the first part of <a target="_blank" href="https://tutorialhell.hashnode.dev/you-dont-know-redis">You don't know Redis</a>, I built an app using Redis as a primary database. For most people, it might sound unusual simply because the key-value data structure seems suboptimal for handling complex data models.</p>
<p>In practice, the choice of a database often depends on the application’s data-access patterns as well as the current and possible future requirements.</p>
<p>Redis was a perfect database for a <a target="_blank" href="https://techforitrecruiters.com/questions/active">Q&amp;A board</a>. I described how I took advantage of <a target="_blank" href="https://redis.io/topics/data-types#sorted-sets">sorted sets</a> and <a target="_blank" href="https://redis.io/topics/data-types#hashes">hashes</a> data types to build features efficiently with less code.</p>
<p>Now I need to extend the Q&amp;A board with registration/login functionality. </p>
<p>I will use Redis again. There are two reasons for that.</p>
<p>Firstly, I want to avoid the extra complexity that comes with adding yet another database.</p>
<p>Secondly, based on the requirements that I have, Redis is suitable for the task. </p>
<p>Important to note, that user registration and login is not always about only email and password handling. Users may have a lot of relations with other data which can grow complex over time. </p>
<p>Despite Redis being suitable for my task, it may not be a good choice for other projects. </p>
<p>Always define what data structure you need now and may need in the future to pick the right database. </p>
<h3 id="implementation">Implementation</h3>
<p>I use serverless functions, the <a target="_blank" href="https://github.com/luin/ioredis">ioredis</a> library and <a target="_blank" href="https://upstash.com/?utm_source=sndr_3">Upstash Serverless Redis</a>.</p>
<p>I can’t help but talk about serverless all the time because it greatly simplifies development. I love when complexity is removed whenever possible and Upstash is doing just that for me. </p>
<p>I have zero work with setting up Redis. Moreover, I am using Upstash both in development and production.</p>
<h4 id="registration-flow">Registration flow</h4>
<p>During registration, we collect the user <code>name</code>, <code>email</code> and <code>password</code>. Before registering a user, we need to make sure that the email has not been registered already (is unique in the system).</p>
<p>Redis does not support constraints. However, we can keep track of all registered emails using a sorted set named <code>emails</code>. </p>
<p>On every new registration, we can use the <a target="_blank" href="https://redis.io/commands/zscore">ZSCORE</a> command to check whether the provided email is already registered.</p>
<p>If the email is taken, we need to notify the user about it. </p>
<p>⚠️ Note, that this isn’t the best option because by telling that a given email is registered we provide a simple way for anyone to check whether someone is registered with a particular service, albeit it’s not a big security issue. </p>
<p>Before we can save a new user, we need to: </p>
<ul>
<li><strong>Generate a unique user <code>ID</code>.</strong></li>
</ul>
<p>We can use the <a target="_blank" href="https://redis.io/commands/incr">INCR</a> command to always get a unique value by incrementing a number stored at a key by one. If the key does not exist, Redis will set it to <code>0</code> before performing the operation. This means that the initial value will be <code>1</code>.</p>
<pre><code><span class="hljs-keyword">const</span> id = <span class="hljs-keyword">await</span> redis.incr(<span class="hljs-string">'user_ids'</span>) <span class="hljs-comment">// -&gt; 1</span>
</code></pre><p>Whenever you need to create a <a target="_blank" href="https://redis.io/commands/incr#pattern-counter">counter</a>, <code>INCR</code> is a great choice. Or you can build a <a target="_blank" href="https://redis.io/commands/incr#pattern-rate-limiter">rate-limiter</a> to protect your API from being overwhelmed by using <code>INCR</code> together with <a target="_blank" href="https://redis.io/commands/expire">EXPIRE</a>. </p>
<ul>
<li><strong>Hash the password with the <a target="_blank" href="https://github.com/kelektiv/node.bcrypt.js/">bcrypt</a> library.</strong></li>
</ul>
<pre><code><span class="hljs-keyword">const</span> hash = <span class="hljs-keyword">await</span> bcrypt.hash(password, <span class="hljs-number">10</span>)
</code></pre><p>Now that we have the unique user <code>ID</code> (e.g. user ID is 7) and the hashed password, we can:
<strong>1. Store user details in a hash under the <code>user:{ID}</code> key.</strong></p>
<pre><code>redis.hmset(<span class="hljs-string">'user:7'</span>, { <span class="hljs-number">7</span>, <span class="hljs-type">name</span>, email, hash })
</code></pre><p>Knowing the <code>ID</code>, we can easily get all user details using the <a target="_blank" href="https://redis.io/commands/hgetall">HGETALL</a> command:</p>
<pre><code><span class="hljs-selector-tag">redis</span><span class="hljs-selector-class">.hgetall</span>(<span class="hljs-string">'user:7'</span>);
</code></pre><p><strong>2. Add the user’s email to the <code>emails</code> sorted set.</strong></p>
<pre><code>redis.zadd(<span class="hljs-string">'emails'</span>, -Math.abs(<span class="hljs-number">7</span>), email)
</code></pre><p>This allows us to lookup emails to check if they are registered or get the user's <code>ID</code> by <code>email</code> which is exactly what we need for the login process. </p>
<p><code>redis.zscore('emails', email)</code> will return the score which is the <code>ID</code> or <code>nil</code> if the email is not found.</p>
<p>Notice how we use this sorted set for two important features, namely ensuring unique emails and looking up users by email. </p>
<p>But we are taking it one step further and set scores (which represent user <code>ID</code>s) as negative numbers to mark emails as unverified: <code>-Math.abs(7)</code>. Then, when the email is verified, we simply convert it to a positive number.</p>
<pre><code>redis.zadd(<span class="hljs-string">'emails'</span>, Math.abs(<span class="hljs-number">7</span>), email)
</code></pre><p>If a specified <code>email</code> is already a member of the <code>emails</code> sorted set, Redis will update the score only.</p>
<p>During the login process, we can always check for negative numbers and request users to verify their email instead of logging them in.</p>
<p>Retrieving all unverified emails is a trivial operation done with the <a target="_blank" href="https://redis.io/commands/zrangebyscore">ZRANGEBYSCORE</a> command.</p>
<pre><code><span class="hljs-selector-tag">redis</span><span class="hljs-selector-class">.zrangebyscore</span>(<span class="hljs-string">'emails'</span>, <span class="hljs-string">'-inf'</span>, -<span class="hljs-number">1</span>, <span class="hljs-string">'WITHSCORES'</span>);
</code></pre><p>Registration function <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/register.js">source code</a></p>
<h4 id="login-flow">Login flow</h4>
<p>Before logging in the user, we check if the provided email exists in our database. As mentioned before, the <code>score</code> is the user <code>ID</code>.</p>
<pre><code><span class="hljs-keyword">const</span> userId = <span class="hljs-keyword">await</span> redis.zscore(<span class="hljs-string">'emails'</span>, email);
</code></pre><p>If so, we first check if the email is verified by making sure the <code>ID</code> is a positive number. If not, we ask users to verify their email.</p>
<p>If the email is verified, we get the password hash that we stored for the user:</p>
<pre><code><span class="hljs-keyword">const</span> hash = <span class="hljs-keyword">await</span> redis.hget(<span class="hljs-string">'user:7'</span>, <span class="hljs-string">'hash'</span>);
</code></pre><p>and check whether the password is correct:</p>
<pre><code><span class="hljs-keyword">const</span> <span class="hljs-keyword">match</span> = <span class="hljs-keyword">await</span> bcrypt.compare(password, hash);
</code></pre><p>If the password is correct, we generate a token and return it to the client.</p>
<p>And we are done.</p>
<p>Login function <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/login.js">source code</a></p>
<h3 id="conclusion">Conclusion</h3>
<p>As you can see, we needed four Redis commands for registration and only two for login. </p>
<p>Probably you noticed that while describing the registration and login process with Redis we also revealed two more use cases for Redis, namely counter and rate-limiting.</p>
<p>Redis has a lot more <a target="_blank" href="https://redislabs.com/redis-best-practices/introduction/">use cases</a> beyond cache and learning about them will only make you even more efficient.</p>
<p>Follow me to read about how I am implementing a secure production-ready registration flow with email verification and password recovery backed by Redis. </p>
<hr />
<p>Check out my article on how I implemented the <a target="_blank" href="https://tutorialhell.hashnode.dev/how-to-create-linkedin-like-reactions-with-serverless-redis">LinkedIn-like reactions with Serverless Redis</a>.</p>
]]></content:encoded></item><item><title><![CDATA[You don't know Redis]]></title><description><![CDATA[In my previous post, I touched on the point that Redis is more than just an in-memory cache. 
Most people do not even consider Redis as a primary database. There are a lot of use cases where Redis is a perfect choice for non-cache related tasks. 
In ...]]></description><link>https://blog.tutorialhell.dev/you-dont-know-redis</link><guid isPermaLink="true">https://blog.tutorialhell.dev/you-dont-know-redis</guid><category><![CDATA[Redis]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Databases]]></category><dc:creator><![CDATA[Sandor]]></dc:creator><pubDate>Thu, 22 Jul 2021 14:11:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1626962906565/7RTlV8E87.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In my previous <a target="_blank" href="https://tutorialhell.hashnode.dev/how-to-create-linkedin-like-reactions-with-serverless-redis">post</a>, I touched on the point that Redis is more than just an in-memory cache. </p>
<p>Most people do not even consider Redis as a primary database. There are a lot of use cases where Redis is a perfect choice for non-cache related tasks. </p>
<p>In this article, I will demonstrate how I built a fully functional Q&amp;A board for asking and upvoting the most interesting questions. <strong>Redis will be used as a primary database</strong>.</p>
<p>I will use Gatsby (React), Netlify serverless functions and <a target="_blank" href="https://upstash.com?utm_source=sndr_2">Upstash Serverless Redis</a>.</p>
<p>Upstash has been a good choice so far and I decided to try it out in a more serious project. I love everything serverless and how it makes things simpler for me. </p>
<p>Serverless will be a great choice for most tasks however you need to know the pros and cons of the tech you are using. I encourage you to learn more about serverless to get the most out of it. </p>
<h3 id="qanda-board-features">Q&amp;A board features</h3>
<p>As you may know, I run a tech newsletter for recruiters where I explain complex tech in simple terms. I have an idea to collect questions from recruiters using a Q&amp;A board and let them vote for questions.</p>
<p>All questions will eventually be answered in my newsletter, however, the most upvoted questions will be addressed first. </p>
<p>Anyone can upvote a question and registration is not required.</p>
<p>Questions will be listed in three tabs:</p>
<ul>
<li>Active - questions sorted by votes and available for voting.</li>
<li>Most recent - questions sorted by date (newest first).</li>
<li>Answered - only questions that have answers.</li>
</ul>
<p><strong>Upvoting</strong> will be one of the most frequently used features and Redis has a data type and optimized commands for it.</p>
<p>A <a target="_blank" href="https://redis.io/topics/data-types#sorted-sets">Sorted set</a> is ideal for this task because all its members are automatically sorted by the score.</p>
<p>Scores are numeric values that we will associate with votes. It is very easy to increment a score (add a vote) by using the <a target="_blank" href="https://redis.io/commands/zincrby">ZINCRBY</a> command. </p>
<p>We will also leverage scores for handling unmoderated questions by setting the score for them to <code>0</code>. All approved questions will have a score of <code>1+</code>. </p>
<p>It allows us to fetch all unmoderated questions by simply using the <a target="_blank" href="https://redis.io/commands/ZRANGEBYSCORE">ZRANGEBYSCORE</a> command specifying the <code>min</code> and <code>max</code> arguments as <code>0</code>. </p>
<p>To fetch all approved questions sorted by the score (highest first) we can use the <a target="_blank" href="https://redis.io/commands/ZREVRANGEBYSCORE">ZREVRANGEBYSCORE</a> command setting the <code>min</code> score argument to <code>1</code>.</p>
<p>This is great that by using just a few Redis commands we can also solve logical tasks along the way. <strong>Lower complexity is a huge benefit</strong>. </p>
<p>We will also use sorted sets for sorting questions by date or filtering questions that have answers. I will explain it in more detail in a moment.</p>
<p>Less frequent operations, namely creating, updating and deleting questions are also easy to accomplish using <a target="_blank" href="https://redis.io/topics/data-types#hashes">hashes</a>. </p>
<h3 id="implementation-details">Implementation details</h3>
<p>The most interesting part is always the actual implementation. I use serverless functions and the <a target="_blank" href="https://github.com/luin/ioredis">ioredis</a> library and I will link the source code explaining what it does.</p>
<p>This article is dedicated to client-facing functionality. Although I will explain admin-related functions, in the final source code there will be no backend interface. You will need to use Postman or a similar tool to call the admin related endpoints.</p>
<p>Let’s take a look at the API endpoints and what they do.</p>
<h3 id="add-a-question">Add a question</h3>
<p>Users can create questions. All questions require moderation before they become visible.</p>
<p>A question is an object and Redis hash is a perfect data type to represent objects. </p>
<p>This is the structure of a questions:
<code>{"datetime":"1633992009", "question":"What are Frontend technologies?", "author":"Alex", "email":"alex@email.com", “score:” “0”, “url”: “www.answer.com” }</code></p>
<p>We will store questions in hashes using the <a target="_blank" href="https://redis.io/commands/HMSET">HMSET</a> command which takes a key and multiple key-value pairs.</p>
<p>The key schema is <code>question:{ID}</code> where <code>ID</code> is the question ID generated using the <a target="_blank" href="https://github.com/uuidjs/uuid">uuid</a> library.</p>
<p>This is a new question and there is no answer yet. We skip the <code>url</code> property but it will be an easy task to add it later using the <a target="_blank" href="https://redis.io/commands/hset">HSET</a> command. </p>
<p>The score for a newly created question is <code>0</code> by default. By our design, it means that this question needs moderation and will not be listed because we only fetch questions with scores starting from <code>1</code>.</p>
<p>Since we keep the score value in a hash, we’ll need to update it whenever it changes. There is a <a target="_blank" href="https://redis.io/commands/hincrby">HINCRBY</a> command that we can use to easily increment values in hashes.</p>
<p>As you can see, using Redis hashes solves a lot more for us than just storing data.</p>
<p>Now that we know how we’ll store questions, we also need to keep track of questions to be able to fetch them later.</p>
<p>For that, we add the <code>ID</code> of a question to a sorted set with a score of <code>0</code> using the <a target="_blank" href="https://redis.io/commands/zadd">ZADD</a> command. A sorted set will allow us to fetch question IDs sorted by scores.</p>
<p>As you can see, we are setting the score to <code>0</code> just like we do it for the <code>score</code> property in the hash above. The reason why we duplicate the score in a hash is that we need it when showing the most recent questions or questions that have answers. </p>
<p>For instance, the most recent questions are stored in a separate sorted set with timestamp as a score hence the original score value is not available unless it’s duplicated in a hash.</p>
<p>Since we store the score in two places, we need to make sure that values are updated both in a hash and in a sorted set. We use the <a target="_blank" href="https://redis.io/commands/multi">MULTI</a> command to execute commands in a manner where either all commands are executed successfully or they are rolled back. Check <a target="_blank" href="https://redis.io/topics/transactions">Redis Transactions</a> for more details.</p>
<p>We will use this approach where applicable. For example, <code>HMSET</code> and <code>ZADD</code> will also be executed in a transaction (see source code below).</p>
<p><code>ZADD</code> command takes a key and our schema for it is <code>questions:{boardID}</code></p>
<p>All questions are mapped to a <code>boardID</code>. For now, it’s a hardcoded value because I need one board only. In the future, I may decide to introduce more boards, for example, separately for Frontend, Backend, QA and so on. It’s good to have the needed structure in place.</p>
<p>Endpoint:
<code>POST /api/create_question</code></p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/question_create.js">create_question</a> serverless function.</p>
<h3 id="approve-a-question">Approve a question</h3>
<p>Before a question becomes available for voting, it needs to be approved. Approving a question means the following:</p>
<ol>
<li>Update the score value in hash from <code>0</code> to <code>1</code> using <a target="_blank" href="https://redis.io/commands/hincrby">HINCRBY</a> command.</li>
<li>Update the score value in the <code>questions:{boardID}</code> sorted set from <code>0</code> to <code>1</code> using the <a target="_blank" href="https://redis.io/commands/ZADD">ZADD</a> command.</li>
<li>Add the question <code>ID</code> to the <code>questions:{boardID}:time</code> sorted set with the timestamp as the score to fetch questions sorted by date (most recent questions) using the same <code>ZADD</code> command.</li>
</ol>
<p>We can get the timestamp by looking up the question by its <code>ID</code> using the <a target="_blank" href="https://redis.io/commands/hget">HGET</a> command.</p>
<p>Once we have it, we can execute the remaining three commands in a transaction. This will ensure that the score value is identical in the hash and the sorted set. </p>
<p>To fetch all unapproved questions the <a target="_blank" href="https://redis.io/commands/ZRANGEBYSCORE">ZRANGEBYSCORE</a> command is used with the <code>min</code> and <code>max</code> values as <code>0</code>. </p>
<p><code>ZRANGEBYSCORE</code> returns elements ordered by a score from low to high while <code>ZREVRANGEBYSCORE</code> - from high to low. We’ll use the latter to fetch questions ordered by the number of votes. </p>
<p>Endpoint for fetching all unapproved questions:
<code>GET /api/questions_unapproved</code></p>
<p>Endpoint for approving a question:
<code>PUT: /api/question_approve</code></p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/questions_unapproved.js">questions_unapproved</a> serverless function. For the most part, this code is similar to other <code>GET</code> endpoints and I will explain it in the next section.</p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/question_approve.js">question_approve</a> serverless function.</p>
<h3 id="fetch-approved-questions">Fetch approved questions</h3>
<p>To fetch all approved questions we use the <code>ZREVRANGEBYSCORE</code> command setting the <code>min</code> argument to <code>1</code> in order to skip all unapproved questions.</p>
<p>As a result, we get a list of IDs only. We will need to iterate over them to fetch question details using the <a target="_blank" href="https://redis.io/commands/hgetall">HGETALL</a> command. </p>
<p>Depending on the number of questions fetched, this approach can become expensive and block the event loop in Node (I am using Node.js). There are a few ways to mitigate this potential problem. </p>
<p>For example, we can use <code>ZREVRANGEBYSCORE</code> with the optional <code>LIMIT</code> argument to only get a range of elements. However, if the offset is large, <a target="_blank" href="https://redis.io/commands/zrangebyscore">it can add up to O(N) time complexity</a>.</p>
<p>Or we can use a Lua script to extend Redis by adding a custom command to fetch question details based on IDs from a stored set without us doing it manually in the application layer. </p>
<p>In my opinion, it would be overhead in this case. Besides that, one must be very careful with Lua scripts because they block Redis and you can’t do expensive tasks with them without introducing performance degradation. This approach may be cleaner however we would still use the <code>LIMIT</code> to avoid large amounts of data.</p>
<p>Always research the pros and cons before the final implementation. As long as you understand the potential issues and have evaluated ways to mitigate them, you are safe.</p>
<p>In my case, I know that it will take significant time before I will have enough questions to face this issue. No need for <a target="_blank" href="https://en.wikipedia.org/wiki/Program_optimization">premature optimization</a>.</p>
<p>Endpoint:
<code>GET /api/questions</code></p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/questions.js">questions</a> serverless function.</p>
<h3 id="vote-for-a-question">Vote for a question</h3>
<p>The process of upvoting a question consists of two important steps that both need to be executed as a transaction.</p>
<p>However, before manipulating the score, we need to check if this question has no answer (<code>url</code> property). In other words, we do not allow anyone to vote for questions that have been answered. </p>
<p>The vote button is disabled for such questions. But we do not trust anyone on the internet and therefore check on the server if a given <code>ID</code> exists in the <code>questions:{boardID}:answered</code> sorted set using the <a target="_blank" href="https://redis.io/commands/zscore">ZSCORE</a> command. If so, we do nothing.</p>
<p>We use the <a target="_blank" href="https://redis.io/commands/hincrby">HINCRBY</a> command to increment the score in the hash by <code>1</code> and the <a target="_blank" href="https://redis.io/commands/zincrby">ZINCRBY</a> command to increment the score in the sorted set by <code>1</code>.</p>
<p>Endpoint:
<code>PATCH /api/question_upvote</code></p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/question_upvote.js">question_upvote</a> serverless function.</p>
<h3 id="fetch-most-recent-approved-questions">Fetch most recent approved questions</h3>
<p>It’s very similar to how we fetch all approved questions with the only difference being that we read another sorted set where the key schema is <code>questions:{boardID}:time</code>. Since we used the timestamp as a score, the <code>ZREVRANGEBYSCORE</code> command returns IDs sorted in descending order.</p>
<p>Endpoint:
<code>PATCH /api/questions_recent</code></p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/questions_recent.js">questions_recent</a> serverless function.</p>
<h3 id="update-a-question-with-an-answer">Update a question with an answer</h3>
<p>Updating or adding new properties to hashes is simple with the <code>HSET</code> command. However, when we add an answer, we move the question from the <code>questions:{boardID}</code> sorted set to the <code>questions:{boardID}:answered</code> one preserving the score.</p>
<p>To do so, we need to know the score of the question and we obtain it using the <a target="_blank" href="https://redis.io/commands/zscore">ZSCORE</a> command. Answered questions will be sorted by score in descending order.</p>
<p>Then we can: </p>
<ol>
<li>update the hash with the <code>url</code> property using the <code>HSET</code> command; </li>
<li>add the hash to the <code>questions:{boardID}:answered</code> sorted set using <code>ZADD</code>;</li>
<li>remove the question from the <code>questions:{boardID}</code> sorted set running the <code>ZREM</code> command.</li>
<li>remove the question from the <code>questions:{boardID}:time</code> sorted set running the <code>ZREM</code> command.</li>
</ol>
<p>All four commands are executed in a transaction. </p>
<p>Endpoint:
<code>PATCH /api/question_add_answer</code></p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/question_add_answer.js">question_add_answer</a> serverless function.</p>
<h3 id="fetch-questions-with-answers">Fetch questions with answers</h3>
<p>Again, the process is similar to fetching all approved questions. This time from the <code>questions:{boardID}:answered</code> sorted set.</p>
<p>Endpoint:
<code>PATCH /api/questions_unswered</code></p>
<p>Here is the source code for the <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis/blob/main/lambda/questions_unswered.js">questions_unswered</a> serverless function.</p>
<hr />
<p>Full <a target="_blank" href="https://github.com/sandorTuranszky/questions-and-answers-board-built-with-redis">source code</a>.
Working <a target="_blank" href="https://techforitrecruiters.com/questions">DEMO</a> on my website.</p>
<h3 id="conclusion">Conclusion</h3>
<p>Redis has a lot of use-cases going way beyond cache. I’ve demonstrated only one of the multiple applications for Redis that one can consider instead of reaching for an SQL database right away.</p>
<p>Of course, if you already use a database, adding yet another one may be an overhead. </p>
<p>Redis is very fast and scales well. Most commercial projects have Redis in their tech stack and often use them as an auxiliary database, not just in-memory cache.</p>
<p>I strongly recommend learning about <a target="_blank" href="https://redislabs.com/redis-best-practices/introduction/">Redis data patterns and best practices</a> to realize how powerful it is and benefit from this knowledge in the long run. </p>
<p>Check my previous article where I created <a target="_blank" href="https://dev.to/sandorturanszky/how-to-create-linkedin-like-reactions-with-serverless-redis-4cad">LinkedIn-like reactions with Serverless Redis</a> if you haven’t already.</p>
<p>Here is <a target="_blank" href="https://dev.to/sandorturanszky/you-don-t-know-redis-part-2-2581">You don't know Redis (Part 2)</a></p>
<p>Follow for more.</p>
]]></content:encoded></item><item><title><![CDATA[How to create LinkedIn-like reactions with Serverless Redis]]></title><description><![CDATA[As a side hustle, I teach tech recruiters web and software development technologies using plain English. It helps them with understanding job specs and resumes and it makes all of us, tech people, happier. 
I run a weekly newsletter and often get fee...]]></description><link>https://blog.tutorialhell.dev/how-to-create-linkedin-like-reactions-with-serverless-redis</link><guid isPermaLink="true">https://blog.tutorialhell.dev/how-to-create-linkedin-like-reactions-with-serverless-redis</guid><category><![CDATA[Redis]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Sandor]]></dc:creator><pubDate>Tue, 20 Jul 2021 14:24:06 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1626622845282/bLl08dA-Y.jpeg" alt="LinkedIn like reactions.jpeg" /></p>
<p>As a side hustle, I teach tech recruiters web and software development technologies using plain English. It helps them with understanding job specs and resumes and it makes all of us, tech people, happier. </p>
<p>I run a weekly newsletter and often get feedback from recruiters via email or LinkedIn DMs.</p>
<p>I thought that I could try to collect feedback using the “Reactions” feature just like LinkedIn or Facebook does. It’s not as informative as personalised messages but is a simple feature that may incentivize more people to provide some general feedback.</p>
<p>Either way, it’s worth trying and as a software developer, I can’t wait to implement it.</p>
<p>This tutorial is about implementing a feature that will be used in real life on my project. </p>
<h3 id="planning">Planning</h3>
<p>As with any feature or project, we start with the planning phase.</p>
<p>I am going to stick with LinkedIn-like reactions because they are more appropriate for the type of content I post. </p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bo72ffqe726lwm6oiuk5.png" alt="Alt Text" /></p>
<p>I will use the Like, Insightful and Curious reactions and will substitute them with 👍, 💡 and 🤔 emojis respectively.</p>
<p>My static website is built with Gatsby. I do not use a database but I need one to store reactions. I need to decide what database to use.</p>
<p>I deploy with Netlify and I use functions for backend related functionality. That means that I go serverless. Ideally, I need a serverless database too to not have to deal with deploying my own DB or overpaying for PaaS with fixed plans.</p>
<p>As of writing this article, I am using Netlify's free tier and can easily go for more features with a paid plan at a very good price. Using a reasonably priced database would be a perfect complement to my current tech stack.</p>
<p>These are the tasks:</p>
<h5 id="1-research-database-options"><strong>1. Research database options.</strong></h5>
<p>I need to find out what serverless databases exist and choose one.</p>
<h5 id="2-create-a-serverless-backend-with-functions-for"><strong>2. Create a Serverless Backend with functions for:</strong></h5>
<ul>
<li>storing reactions and incrementing/decrementing the count</li>
<li>fetching reactions by a post id</li>
</ul>
<h5 id="3-create-the-reactions-component"><strong>3. Create the "reactions" component.</strong></h5>
<p>Gatsby is based on React and I will build a simple “reactions” component.</p>
<h5 id="4-put-it-all-together-to-make-my-static-website-a-little-bit-dynamic"><strong>4. Put it all together to make my static website a little bit dynamic.</strong></h5>
<p>Static websites can have dynamic features and it’s what makes them, static site generators so incredibly awesome. </p>
<p>In this tutorial, I will focus on the first two tasks. The “reactions" component implementation you can check in the  <a target="_blank" href="https://github.com/sandorTuranszky/gatsby-starter-blog-with-LinkedIn-like-reactions/tree/main/src/components">source code</a></p>
<h3 id="research">Research</h3>
<p>This second phase in Software Development Life Cycle (SDLC) is named Prototyping but I call it Research in this tutorial because I will skip the proof of concept (POC) part.</p>
<p>Research is always fun because it provides a great opportunity to learn about new technologies. While this process is interesting, it can also take a lot of time if we do not make our research more specific. </p>
<p>SQL and NoSQL are the most common database types. The choice isn’t difficult if we know what data will be stored. Let’s quickly take a look at what data structure we will have.</p>
<p>Every <strong>post has a set of reactions</strong> and we need to <strong>count</strong> those <strong>reactions</strong>.</p>
<p>Since I simply want to get an idea about how people react to my posts, I will not require them to log in or limit the types of reactions. </p>
<p>Based on the above, our data structure could look as follows for a post with 3 likes, 12 insightful and 7 curious reactions: <code>{ "like":3, "insightful":12, "curious":7 }</code></p>
<p>A NoSQL database looks like a good choice for storing and manipulating a data structure like the above. </p>
<p>I immediately thought of MongoDB and Redis. However, based on how we will manipulate data, namely persist it once and then increment or decrement certain values, I decide in favor of Redis.</p>
<p>The reason being is that Redis has built-in and performance-optimized commands to support what we need.</p>
<p>Besides that, I found a serverless Redis database <a target="_blank" href="https://upstash.com?utm_source=sndr_1">Upstash</a> which looks simple and has reasonable pricing including a free plan. I like starting free and paying as I scale.</p>
<p>Note that we are using Redis as a <strong>primary database</strong>. Redis can be configured to write data to disk which provides a degree of <a target="_blank" href="https://redis.io/topics/persistence">data safety</a> comparable to what PostgreSQL offers.</p>
<p>Redis solves a much wider range of problems than just in-memory caching and can be used either as a primary database or as an additional database for solving problems that other databases struggle with.</p>
<p>I like that Upstash <a target="_blank" href="https://docs.upstash.com/overall/durability?utm_source=sndr_1">enables persistence</a> by default keeping data both in memory and disk. This removes the headache of configuring things which would be an overhead for a task like this one. This is why I always use serverless and PaaS whenever possible.</p>
<p>To sum up this part, let me share with you an interesting <a target="_blank" href="https://redislabs.com/ebook/redis-in-action/">free e-book</a> called “Redis in Action” packed with valuable information and use-cases for Redis.</p>
<h3 id="serverless-backend">Serverless Backend</h3>
<p>I will use Netlify’s serverless functions with Node instead of creating my own backend. You are free to use any backend architecture. </p>
<p>The easiest way to connect Redis with Upstash is to use the <a target="_blank" href="https://github.com/NodeRedis/node-redis">redis-client</a> as described <a target="_blank" href="https://docs.upstash.com/howto/connectwithtls?utm_source=sndr_1">here</a>.</p>
<p>First things first, we need to create a Serverless Redis database following this <a target="_blank" href="https://docs.upstash.com?utm_source=sndr_1">Getting Started guide</a>.</p>
<p>Please, note that I leave out the <a target="_blank" href="https://docs.upstash.com/overall/consistency?utm_source=sndr_1">Strong Consistency Mode</a>, because Eventual Consistency is suitable for my task.</p>
<p>This is the schema for naming the keys: <strong>post:{id}:{reaction}</strong></p>
<ol>
<li><strong>post:{id}:like</strong> -&gt; <code>post:856f9d0a:like</code></li>
<li><strong>post:{id}:insightful</strong> -&gt; <code>post:856f9d0a:insightful</code></li>
<li><strong>post:{id}:curious</strong> -&gt; <code>post:856f9d0a:curious</code> </li>
</ol>
<p>We could go with the most basic kind of Redis value known as <a target="_blank" href="https://redis.io/topics/data-types#strings">Strings</a>. But we’ll go with <a target="_blank" href="https://redis.io/topics/data-types#hashes">hashes</a> because we want to store objects as value and it is advisable to <a target="_blank" href="https://redis.io/topics/memory-optimization">use hashes when possible</a>.</p>
<p>This is how we do it for a given post ID:</p>
<ul>
<li>To increment a reaction by 1, for example, “Like”, we will use the <a target="_blank" href="https://redis.io/commands/hincrby">HINCRBY</a> command. If the key does not exist, it will create the key and set its value to 0 before incrementing. If the key does exist, it will simply increment by the value we provide. It allows us to reuse this function both for creating and updating reactions.</li>
</ul>
<p><code>HINCRBY post:856f9d0a:reactions like 1</code></p>
<p>Here is the <a target="_blank" href="https://github.com/sandorTuranszky/gatsby-starter-blog-with-LinkedIn-like-reactions/blob/main/lambda/react.js">implementation</a></p>
<p>If we had to decrement reactions for cases when a reaction is removed or changed, we would simply pass the value to be incremented by a negative number: -1</p>
<ul>
<li>To read reactions for a post ID we’ll use the <a target="_blank" href="https://redis.io/commands/hgetall">HGETALL</a> command which returns key-value pairs:</li>
</ul>
<p><code>HGETALL post:856f9d0a:reactions</code> -&gt; <code>// will return {"like":"3","insightful":"1","curious":"2"}</code></p>
<p>Here is the <a target="_blank" href="https://github.com/sandorTuranszky/gatsby-starter-blog-with-LinkedIn-like-reactions/blob/main/lambda/reactions.js">implementation</a></p>
<p>With this approach, knowing the post ID, we can efficiently set, update and retrieve reactions for a post with a ridiculously small amount of code.</p>
<p>Post IDs are not short but we will use them for naming keys because they will not cause any noticeable memory usage increase in our case. </p>
<p>But you should always keep in mind that along with having a readable key naming schema, you need to control the length of keys. Long keys can use more memory and even cause performance implications as described in the <a target="_blank" href="https://redis.io/topics/data-types-intro#redis-keys">Redis keys</a> section.</p>
<h3 id="off-topic">Off-topic</h3>
<p>Even though this is not directly related to this tutorial, I know that later I will want to show the most popular posts based on reactions. </p>
<p>To get posts with the most Likes, Insightful and Curious reactions, we need to track them using a <a target="_blank" href="https://redis.io/topics/data-types#sorted-sets">sorted set</a>.</p>
<p>For instance, this is how we store a post that received a Like reaction:
<a target="_blank" href="https://redis.io/commands/zincrby">ZINCRBY</a> <code>reaction:like 1 post:856f9d0a</code></p>
<p>And this is how we get the most liked 5 posts:
<a target="_blank" href="https://redis.io/commands/zrevrangebyscore">ZREVRANGEBYSCORE</a> <code>reaction:like +INF -INF withscores LIMIT 0 5</code></p>
<p>I will provide more details and a working implementation in one of my next posts.</p>
<p>It’s always a good idea to design a system taking into account all known future requirements and choose technologies that will support them in the future.</p>
<hr />
<p>Here is a working implementation on my <a target="_blank" href="https://techforitrecruiters.com/blog">website</a>. Pick any <a target="_blank" href="https://techforitrecruiters.com/blog/2021-05-02-what-is-a-content-management-system/">post</a> and you will find reactions at the bottom. The source code you can find <a target="_blank" href="https://github.com/sandorTuranszky/gatsby-starter-blog-with-LinkedIn-like-reactions">here</a></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2j18fogq7ge56vjjouh.png" alt="Alt Text" /></p>
<h3 id="conclusion">Conclusion</h3>
<p>If you still perceive Redis as an in-memory cache, get ready because I have more posts coming up that cover powerful features backed by this amazing database. </p>
<p>The next post will be about <a target="_blank" href="https://dev.to/sandorturanszky/you-don-t-know-redis-3onh">how I built a Q&amp;A board</a> for asking and upvoting the most interesting questions using Redis. </p>
<p>Follow for more!</p>
]]></content:encoded></item></channel></rss>